Continue to Site

Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations KootK on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

Matlab for loop

Status
Not open for further replies.

mechMH

Mechanical
Apr 17, 2018
4
Hi everyone,
i'm working on a code which has two 5*3 matrices,I want to add each column in say matrix "A" to every column in matrix "B"
so the resultant matrix is 5*9.
I'm doing it with FOR loop but it only returns the final column values. I hope if there are any suggestions!
 
Replies continue below

Recommended for you

There are neater ways of doing this, but using loops is robust

Out_matrix=zeros(5,9);
for jj=0:2
for kk=1:3
Out_matrix:),(jj*3)+kk)=A:),jj+1)+B:),kk);
end
end


Cheers

Greg Locock


New here? Try reading these, they might help FAQ731-376
 
If you are doing loops, bear in mind two things:

1) Pre-allocate your array (Greg's first line). Never grow it.
2) Realise that the neat and satisfying one-liners (vectorized solutions) don't have as much advantage over loops these days.


Steve
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor