Efficient implementation for loops

I have a for loop which is slowing down the performance, which I'm sure there is a way to speed it up but I don't know how.
Suppose you have two matrices
A = randn(4,2,10); B = randn(2,10);
The result you want is C of dimension 4 * 10. In a for loop implementation, it is:
for i = 1 : 10
C(:,i) = A(:,:,i) * B(:,i)
end
How can I get C without using for loops?
Thanks in advance

回答 (1 件)

Sean de Wolski
Sean de Wolski 2015 年 7 月 14 日

1 投票

Preallocating C will make this much faster:
Before the loop:
C = zeros(4,10);

4 件のコメント

Tao Yang
Tao Yang 2015 年 7 月 14 日
Thanks.
Is there a way to avoid the for loop?
Sean de Wolski
Sean de Wolski 2015 年 7 月 14 日
Yeah, it could be rewritten as a larger matrix multiplication with a few reshapes and permutes but why bother? It's already blazingly fast!
Let me make it a little bigger and time it:
A = randn(400,20,10000);
B = randn(20,10000);
tic
C = zeros(400,10000);
for i = 1:10000
C(:,i) = A(:,:,i)*B(:,i);
end
toc
So now I'm doing a whole lot more math in (on my wimpy laptop) ... drum roll
Elapsed time is 0.213792 seconds.
Less than a quarter of a second!
Loops aren't slow in MATLAB. Inefficiencies within loops like not preallocating slow MATLAB down.
Tao Yang
Tao Yang 2015 年 7 月 14 日
Thanks Sean.
Actually I simplified the original question. The above operation is just a small part of my entire code and needs to be repeated a lot of times (I'm running a big Monte Carlo simulations).
So I would appreciate if you could help me with the loop-free solution.
Many thanks, Tao
Sean de Wolski
Sean de Wolski 2015 年 7 月 16 日
Have you profiled it to see if that is the bottleneck?

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

カテゴリ

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

製品

質問済み:

2015 年 7 月 14 日

コメント済み:

2015 年 7 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by