Simplification of "for" loop MATLAB R2018a

조회 수: 1 (최근 30일)
GIorgi Tsutskiridze
GIorgi Tsutskiridze 2018년 4월 26일
댓글: GIorgi Tsutskiridze 2018년 4월 26일
I want to perform the following procedure:
I have two vectors x=[1,2,3] and y=[5,7,9]
I want to take first element of x and then add each element from y to it, then I want to take second element from x and add each element from y to it and so on... Finally, I want to save each result from each step of this procedure in a vector of the corresponding size. I know in advance that I will get the following vector r =[6,8,10,7,9,11,8,10,12].
In order to perform the following procedure I have written the following script:
clear
a = 1;
b = 3;
c = 5;
d = 2;
e = 9;
x = [a:b];
y = [c:d:e];
[rx,cx] = size(x);
[ry,cy] = size(y);
r = zeros((cx*cy),1);
for ii = x
for jj = y
xi = find(x==ii)
yi = find(y==jj)
row = xi*cy-(cy-yi)
r(row) = ii + jj
end
end
Finally, I got the result but I spent about 2 hours to come up with that. (well, I am just beginner in programming). I would be happy to know if there is any simpler and more efficient way to do that. I am especially concerned about this step, since it took the most of my time. Or should I give up coding since I took for so long for so simple problem?
xi = find(x==ii)
yi = find(y==jj)
row = xi*cy-(cy-yi)
r(row) = ii + jj

채택된 답변

Birdman
Birdman 2018년 4월 26일
편집: Birdman 2018년 4월 26일
By the power of implicit expansion starting from R2016b in MATLAB, your desire can be achieved in one line of code:
r=reshape((x.'+y).',1,[])
Read the following blog to understand implicit expansion:
Note that (x.'+y).' part refers to implicit expansion. Since they have a dimension mismatch, MATLAB internally adjusts their dimensions to allow them to be summed.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by