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 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