Clear Filters
Clear Filters

Simplification of "for" loop MATLAB R2018a

1 view (last 30 days)
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

Accepted Answer

Birdman
Birdman on 26 Apr 2018
Edited: Birdman on 26 Apr 2018
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.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!