how to create a matrix from a loop using other matrix

1 回表示 (過去 30 日間)
Adhish Aggarwal
Adhish Aggarwal 2017 年 7 月 11 日
回答済み: Andrei Bobrov 2017 年 7 月 12 日
c = [1
2
3
4
5
6
7
8
9
10];
d = [1
0
0
-1
0
0
1
0
1
1];
i = zeros(numel(d),1);
for i1 = 2:numel(i)
if d(i1) == 1
i(i1) = c(i1);
elseif d(i1) == -1
i(i1) = c(i1)*-1;
else
i(i1) = i(i1-1);
end
end
  2 件のコメント
Rik
Rik 2017 年 7 月 11 日
So, what is your question? I only see some unformated code.
Have a read here and here. It will greatly improve your chances of getting an answer.
dpb
dpb 2017 年 7 月 12 日
How to vectorize I presume is the ?
? to OP, though...your loop will only set the value to succeeding for those after the first as it is sequential and passes by the first element. Is this intended or is it intended that all elements in i end up nonzero in the end?
Also, while I don't have an issue with using i as a loop index or temporary in defiance of the builtin definition, I would recommend to NOT use it as a result variable array as here. Pick another variable name for the real case.

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

回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2017 年 7 月 12 日
out = d.*c;
t = d ~= 0;
cc = out(t);
out = cc(cumsum(t));

カテゴリ

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