Ali
Ali

Reputation: 35

Dynamic for loop in Matlab

I want to calculate certain array but the issue that I am facing is that array is changing in each iteration. I want to print

for n=1 
    s(1)u(1)
for n=2
    s(2)u(1)+(s(1)-s(2))u(2)
for n=3
    s(3)u(1)+(s(2)-s(3))u(2)+(s(1)-s(2))u(3)

and so on

Upvotes: 0

Views: 222

Answers (1)

Steve
Steve

Reputation: 4097

The best way to do this depends on your setup. If you just want to do a matrix/vector operation without many loops, note that this looks almost like an inner product between s reversed and u except some terms have been turned into the difference. If I understand your equations, it looks like this:

N = 12;
s_all = 1:N;
u_all = 7:N+6


for M = 1:N
   s = s_all(1:M);
   u = u_all(1:M);

   ds = s - [s(2:end) 0];
   result = u*ds(end:-1:1)'
end

Note my data is a row vector.

this works fine if N doesn't grow too big, if you don't know the final size of N at the start, or if the values of s and u all change at each iteration.

Depending on the sizes of your data, if u and s have the same prior values at each iteration you might see better results by preallocating u and s above the for loop and then bring in new values one at a time rather than copying over new s and u and recalculating the entire ds value.

Like this:

s = nan(1,N);
u = nan(1,N);
ds = nan(1,N);

for M = 1:N
   s(M) = s_all(M);
   u(M) = u_all(M);

   if(M>1)
     ds(M-1) = s(M-1) - s(M);
   end
   ds(M) = s(M);
   result = u(1:M)*ds(M:-1:1)'
end

Upvotes: 1

Related Questions