julianfperez
julianfperez

Reputation: 1744

Simple Speed-up of code

It is known that MATLAB works slow with for loop. I have tried to vectorize the following code without success. Perhaps I am wrong with the implementation.

for I = NS2:-1:1
         A = 0;
         for J=1:8
            A = A + KS2(J,I)*FA(J);
         end
         S2 = S2 + ( SS2(1,I)*sin(A) + SS2(2,I)*cos(A) );
      end

where: FA = matrix 1x8

KS2 = matrix 8x25

SS2 = matrix 2x25

A = scalar

S2 = scalar

I try to improve it in this way:

A = 0;
J = 1:8;
for I = NS2:-1:1

 A = FA(1,J)*KS2(J,I);

 S2 = S2 + ( SS2(1,I)*sin(A) + SS2(2,I)*cos(A) );
 end

However, the runtime for this improvement is similar to the original code.

Upvotes: 2

Views: 100

Answers (1)

gnovice
gnovice

Reputation: 125854

Try this instead (no loops):

A = (FA*KS2).';  %'# A is now 25-by-1
S2 = SS2(1,:)*sin(A) + SS2(2,:)*cos(A);

Upvotes: 4

Related Questions