user3593525
user3593525

Reputation: 253

Matlab's trick to increment variable

How to increment a variable by a infinite set of numbers, in Matlab. I'v a variable which I want to increment till the loop ends by 0.1 every time but through set of range. I'm currently doing this by: K=K*0.1; %K = 2 initially but I want this same by Matlab's trick of ranged values like [0.1:0.1:9] where 9 is the loop condination.

My Code:

K=2;
for ii=1:9
K=K*0.1;
end

Upvotes: 0

Views: 4602

Answers (2)

Geoff
Geoff

Reputation: 1603

You can try using the cumprod command which returns the cumulative product of the elements in a matrix or vector. For your example, something like:

K=cumprod([2 repmat(0.1,1,9)]);  % returns a row vector of 9 elements

repmat just creates a row vector of nine elements each set to the value 0.1. The last element in the vector, K(end), will be the product returned by your example. i.e.K = 2*0.1^9;

Upvotes: 0

Luis Mendo
Luis Mendo

Reputation: 112679

If I understand correctly:

for K = 2 * 0.1.^(1:9)
    %// do something with K
end

Upvotes: 3

Related Questions