Fast matrix multiplication in loop

조회 수: 7 (최근 30일)
Batuhan
Batuhan 2014년 2월 7일
편집: Matt J 2014년 2월 7일
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일
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일
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일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by