How to avoid that loop

4 views (last 30 days)
Alberto Menichetti
Alberto Menichetti on 3 May 2016
Commented: Steven Lord on 3 May 2016
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 Comments
the cyclist
the cyclist on 3 May 2016
Edited: the cyclist on 3 May 2016
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 on 3 May 2016
I'm sorry you're right
k = ones(size(v), 1);

Sign in to comment.

Accepted Answer

the cyclist
the cyclist on 3 May 2016
If my speculation about what you meant it correct, then
k = cumprod(v)/v(1)
  2 Comments
Alberto Menichetti
Alberto Menichetti on 3 May 2016
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 on 3 May 2016
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)])

Sign in to comment.

More Answers (0)

Categories

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

Products

Community Treasure Hunt

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

Start Hunting!