How to multiply two matrices

조회 수: 1 (최근 30일)
carlas
carlas 2011년 11월 24일
Hello,
For example I would like to multiply the following two matrices:
A = rand([10,10,10]);
B = rand([10,10,10]);
defined by:
for i=1:size(A,3)
C(:,:,i)= A(:,:,i)*B(:,:,i);
end
The question is: is this possible without the use of a for loop? Kind regards, Carlas
  댓글 수: 2
umar siyab
umar siyab 2011년 11월 24일
no its not possible without the use of loop because u have to multiply every element in the matrix with other matrix..
Jan
Jan 2011년 11월 24일
What are the real dimensions in your problem? It matters if size(A, 3) is much larger or much smaller than size(A, 1) and size(A, 2).

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

채택된 답변

Andrei Bobrov
Andrei Bobrov 2011년 11월 24일
[m n p]= size(A);
o1 = ones(p,1));
out = cell2mat(cellfun(@mtimes,mat2cell(A,m,n,o1),mat2cell(B,m,n,o1),'un',0));
ADD
[m,n,p] = size(A);
out0 = bsxfun(@times,reshape(A,m,[]),reshape(permute(B,[1 3 2]),1,[],n));
out = reshape(sum(reshape(permute(out0,[1 3 2]),m,m,n,[]),3),m,n,[]);
or for out
out = permute(blockproc(out0,[m n],@(block_struct)sum(block_struct.data,2)),[1 3 2]);

추가 답변 (3개)

Titus Edelhofer
Titus Edelhofer 2011년 11월 24일
Hi Carlas,
probably yes. But in this case probably the loop is not your worst option, as long as you initialize
C = zeros(size(A,2), size(B,1), size(A,3));
before the loop.
Titus
  댓글 수: 1
Jan
Jan 2011년 11월 24일
I do not completely agree with you, Titus: Instead of "not the worst" I'd claim, it is at least "very good". +1
James Tursa's MTIMESX (http://www.mathworks.com/matlabcentral/fileexchange/25977-mtimesx-fast-matrix-multiply-with-multi-dimensional-support ) can handle such tasks efficiently.

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


carlas
carlas 2011년 11월 24일
A = rand([10,10,10]);
[m n p]= size(A);
tic
o1 = ones(p,1);
out = cell2mat(cellfun(@mtimes,mat2cell(A,m,n,o1),mat2cell(A,m,n,o1),'un',0));
t1 = toc;
tic
C = zeros([10,10,10]);
for i=1:size(A,3)
C(:,:,i) = A(:,:,i)'*A(:,:,i);
end
t2 = toc;
xFaster = t2/t1
xFaster =
0.5072
The for loop is faster. Based on the above answers I assume that the for loop is the most optimal implementation if the final matrix is initialized. However, it is possible to do without.
  댓글 수: 1
Jan
Jan 2011년 11월 24일
I definitely prefer the loop. Especially for large inputs it has a much smaller memory footprint than the CELL method. For A=rand(100,100,1000) the loop is 3 times faster.

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


carlas
carlas 2011년 11월 24일
Thanks Titus and Andrei!

카테고리

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