w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to make a for loop for addition of value from previous iteration into current iteration?

If you want to construct such a vector in a loop, try the following:

v = zeros(n, 1);
for i=1:n
    if (i==1)
        v(i) = a;
    elseif (mod(i,2)==0)
        v(i) = v(i-1)+b;
    else
        v(i) = v(i-1)+c;
    end
end

Alternatively, without using loop, as follows:

v=[a,repmat([b,c],[1,(n-1)/2])];
v=cumsum(v)';




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.