How to avoid that loop

4 ビュー (過去 30 日間)
Alberto Menichetti
Alberto Menichetti 2016 年 5 月 3 日
コメント済み: Steven Lord 2016 年 5 月 3 日
k(1) = 1;
for i=2:size(k)
k(i) = k(i-1)*v(i)
end
v(i) is a scalar and it's different on every iteration How could I do that without using a loop?
  2 件のコメント
the cyclist
the cyclist 2016 年 5 月 3 日
編集済み: the cyclist 2016 年 5 月 3 日
As written, this loop will never be executed, because size(k) is 1, and
for i = 2:1
<stuff>
end
will have zero iterations.
Some coding mistake? Maybe you meant length(v)?
Alberto Menichetti
Alberto Menichetti 2016 年 5 月 3 日
I'm sorry you're right
k = ones(size(v), 1);

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

採用された回答

the cyclist
the cyclist 2016 年 5 月 3 日
If my speculation about what you meant it correct, then
k = cumprod(v)/v(1)
  2 件のコメント
Alberto Menichetti
Alberto Menichetti 2016 年 5 月 3 日
I think I didn't explain my problem very well:
k(1) = 1
I want
k(i) = k(i-1)*v(i)
for every i>1
Steven Lord
Steven Lord 2016 年 5 月 3 日
No, we understand you. Another approach that doesn't involve division:
v = randperm(8) % Sample data for demonstration purposes
k = cumprod([1 v(2:end)])

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

その他の回答 (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