Fastest way to multiply matrices within an array without for loop?
7 次查看(过去 30 天)
显示 更早的评论
Hi everyone,
I have a 3d matrix, which is made up of an array of 2x2 matrices. I need to perform matrix multiplication of all the 2x2 sub-matrices within this 3d structure. I currently have a solution implemented with for loops, but I was wondering if there was an optimized way to do this (possibly with vectorization, using some in-built matlab function, using cell arrays, restructuring the way the data is stored itself, etc). I added an illustration of the concept below, as well as my current implementation using for loops.
Visual Illustration
Overall Matrix Dimension: 2x2xn (I used n=5 for both the visual and code example)
I'm trying to vectorize the matrix product of M1, M2, M3 ... Mn

Code Example
% Length of 3rd dimension
n = 5;
% Initialize random matrix
A = randn(2,2,n);
product = eye(2);
% Calculate product of matrix across 3rd dimension
tic
for i = 1:n
product = product * A(:,:,i);
end
toc
Thank you!
2 个评论
Bruno Luong
2021-8-6
The for loop is very well, no need to find an alternative (and there is none for good reason).
You might save one multiplcation by initialize product with M1 and loop from 2 onward.
回答(1 个)
Matt J
2021-8-6
编辑:Matt J
2021-8-6
(possibly with vectorization, using some in-built matlab function, using cell arrays
If your matrices start off in cell array form, it would indeed be faster to keep them that way:
% Number of matrices
n = 1e5;
% Random matrix data
A(:,:,1:n) = {randn(2,2)};
product = eye(2);
%Cell form
tic;
for i = 1:n
product = product * A{i};
end
toc;
%Matrix form
tic
A=cell2mat(A);
for i = 1:n
product = product * A(:,:,i);
end
toc
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!