Fast matrix multiplication in loop

Dear All,
I have two matrices with dimensions 3x3 and E6x3. I need to multiply each row of the latter with the former. It's like
a=rand(3,3);
b=(1000000,3);
for i=1:size(b,1)
c=a*b(i,:)';
end
However, this step takes hours to be done. I wonder if there is any faster way to do this.
Cheers.

1 件のコメント

Jos (10584)
Jos (10584) 2014 年 2 月 7 日
element-by-element or matrix multiplications?

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

 採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 2 月 7 日
編集済み: Azzi Abdelmalek 2014 年 2 月 7 日

1 投票

a=rand(3,3);
b=rand(100,3);
n=size(a,2);
m=size(b,1);
c=zeros(m,n);
for i=1:size(b,1)
c(i,:)=a*b(i,:)';
end
%or simply
c=(a*b')'

その他の回答 (2 件)

Jos (10584)
Jos (10584) 2014 年 2 月 7 日

0 投票

Two options:
1. pre-allocate C to avoid memory allocation in each iteration
C = zeros(N, ..) % pre-allocation
for k = 1:N,
C(k,:) = ..
end
2. Use BSXFUN

1 件のコメント

Batuhan
Batuhan 2014 年 2 月 7 日
Thank you. But I'm not sure if bsxfun is the right one, since
C=bsxfun(@times,a*b) results in
Error using bsxfun Non-singleton dimensions of the two input arrays must match each other.

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

Batuhan
Batuhan 2014 年 2 月 7 日

0 投票

Thank you all. Really, preallocation was the issue and fixes it.

1 件のコメント

Matt J
Matt J 2014 年 2 月 7 日
編集済み: Matt J 2014 年 2 月 7 日
No, it's crazy to do this with a loop, pre-allocated or otherwise. Just do c=b*a', as Azzi noted.

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

カテゴリ

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

質問済み:

2014 年 2 月 7 日

編集済み:

2014 年 2 月 7 日

Community Treasure Hunt

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

Start Hunting!

Translated by