Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
how to vectorize a double loop

Subject: how to vectorize a double loop

From: luigi vacca

Date: 18 Jan, 2010 17:31:05

Message: 1 of 2

Hi There,

How do you vectorize this code?

for i=n:-1:1
    for j=1:(2*i-1 )
      s(j) = s(j)*edx;
      C(j) = max(disc*(pu*C(j)+pm*C(j+1)+pd*C(j+2)),K-s(j));
    end
end

Thanks

Subject: how to vectorize a double loop

From: Jan Simon

Date: 18 Jan, 2010 23:51:02

Message: 2 of 2

Dear Luigi!

> How do you vectorize this code?
>
> for i=n:-1:1
> for j=1:(2*i-1 )
> s(j) = s(j)*edx;
> C(j) = max(disc*(pu*C(j)+pm*C(j+1)+pd*C(j+2)),K-s(j));
> end
> end

dpu = disc * pu;
dpm = disc * pm;
dpd = disc * pd;

 for i=n:-1:1
     s = s .* edx;
     KminusS = K - s;
     d = 2*i-1;
     C(1:d) = max(dpu * C(1:d) + dpm * C(2:d+1) + dpd * C(3:d+2), ...
                   KMinusS(1:d))
 end

You can save a further multiplication by dividing dpm, dpd, K and the initial s by dpu.

Good luck, Jan

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us