Hi,
I made a 2d matrix with two for loops:
for k = 1:32
for l = 1:32
P_new(l,k) = P_old(l) + (LODF(l,k) * P_old(k));
end
end
P_old is here a 32 x 1 matrix and LODF is a 32 x 32 matrix which is already computed. How can I vectorize this code to avoid the for loops? Thanks in advance.

 採用された回答

Matt J
Matt J 2013 年 12 月 10 日

0 投票

P_new= bsxfun(@times, LODF, P_old.');
P_new= bsxfun(@plus, P_new,P_old);

2 件のコメント

Jip
Jip 2013 年 12 月 10 日
編集済み: Matt J 2013 年 12 月 10 日
Although this code avoids the for loops, it is not faster, which is my purpose. Actually the code is much slower. Any other suggestions?
Matt J
Matt J 2013 年 12 月 10 日
編集済み: Matt J 2013 年 12 月 10 日
For 32x32 data, I wouldn't be surprised if the for-loop was the fastest approach. For larger sizes, however, the vectorized approach will start to show superior performance, e.g.,
N=3200;
LODF=rand(N); P_old=rand(N,1);
tic;
P_new=zeros(size(LODF));
for k = 1:N
for l = 1:N
P_new(l,k) = P_old(l) + (LODF(l,k) * P_old(k));
end
end
toc;
%Elapsed time is 0.102201 seconds.
tic;
P_new= bsxfun(@times, LODF, P_old.');
P_new= bsxfun(@plus, P_new,P_old);
toc
%Elapsed time is 0.043591 seconds.
If you're not happy with the speed of your code, you should show us the slow part in its entirety. The small part you've shown is pretty fast, in and of itself.

サインインしてコメントする。

その他の回答 (2 件)

Jos (10584)
Jos (10584) 2013 年 12 月 10 日

0 投票

for loops are pretty fast when you use pre-allocation
P_new = zeros(32,32) ;
for k = 1:32
for l = 1:32
P_new(l,k) = P_old(l) + (LODF(l,k) * P_old(k));
end
end
Jip
Jip 2013 年 12 月 10 日

0 投票

Yes I know, I already did that.

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

Jip
2013 年 12 月 10 日

編集済み:

2013 年 12 月 10 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by