Fastest way to multiply matrices within an array without for loop?

조회 수: 7 (최근 30일)
Megan Ross
Megan Ross 2021년 8월 6일
편집: Matt J 2021년 8월 6일
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
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
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;
Elapsed time is 0.033400 seconds.
%Matrix form
tic
A=cell2mat(A);
for i = 1:n
product = product * A(:,:,i);
end
toc
Elapsed time is 0.127890 seconds.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by