How to multiply two matrices
2 次查看(过去 30 天)
显示 更早的评论
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
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
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
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]);
0 个评论
更多回答(3 个)
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
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!