Simple Piece of Code for improvement
Afficher commentaires plus anciens
Hi. 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:
NS2 = 25
FA is a matrix 1x8
KS2 is a matrix 8x25
SS2 is a matrix 2x25
A is a scalar
S2 is a 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.
1 commentaire
Fangjun Jiang
le 23 Août 2011
Please see my comparison post. There is a solution without any for-loop and it is much faster.
Réponse acceptée
Plus de réponses (3)
Jan
le 23 Août 2011
Move the indexing out of the loop:
A = 0;
FAJ = FA(1, 1:8);
KS2J = KS2(1:8, :);
SS21 = SS2(1, :);
SS22 = SS2(2, :);
for I = NS2:-1:1
A = FAJ * KS2J(:, I);
S2 = S2 + (SS21(I) * sin(A) + SS22(I) * cos(A));
end
How much does this help?
In general "X(1:8)" is faster than "J=1:8; X(J)", because for the first case the boundaries are checked for the first and last element only.
3 commentaires
Sean de Wolski
le 23 Août 2011
Interesting about the boundary checking!
Julián Francisco
le 23 Août 2011
Jan
le 23 Août 2011
@Julian: You are right, for this case KS2J is not very helpful at first sight. I've shown this for educational reasons only. The actual acceleration is coming from using "KS2J(:, I)" instead of "KS2(J, I)" and I've limited the 1st dimension of KS2J to allow to use the colon even if the original KS2 is larger.
Fangjun Jiang
le 23 Août 2011
See if the following gives correct result and fast speed.
A=FA*KS2;
S2=sum(sum(SS2.*[sin(A);cos(A)]));
1 commentaire
Fangjun Jiang
le 23 Août 2011
Previously it missed the right ']'
William
le 23 Août 2011
1 vote
To speed things up make an array of zeros
zeros( however big you need it)
then perform operation on each member of the array. So basically you want to allocate space for the loop prior to doing any operations.
1 commentaire
Julián Francisco
le 23 Août 2011
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!