简体   繁体   中英

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.

Try this instead (no loops):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM