Simplification of "for" loop MATLAB R2018a

1 回表示 (過去 30 日間)
GIorgi Tsutskiridze
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.
  1 件のコメント
GIorgi Tsutskiridze
GIorgi Tsutskiridze 2018 年 4 月 26 日
This is amazing. Thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by