Simple Piece of Code for improvement
古いコメントを表示
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 件のコメント
Fangjun Jiang
2011 年 8 月 23 日
Please see my comparison post. There is a solution without any for-loop and it is much faster.
採用された回答
その他の回答 (3 件)
Jan
2011 年 8 月 23 日
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 件のコメント
Sean de Wolski
2011 年 8 月 23 日
Interesting about the boundary checking!
Julián Francisco
2011 年 8 月 23 日
Jan
2011 年 8 月 23 日
@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
2011 年 8 月 23 日
See if the following gives correct result and fast speed.
A=FA*KS2;
S2=sum(sum(SS2.*[sin(A);cos(A)]));
1 件のコメント
Fangjun Jiang
2011 年 8 月 23 日
Previously it missed the right ']'
William
2011 年 8 月 23 日
1 投票
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.
カテゴリ
ヘルプ センター および File Exchange で MATLAB についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!