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

7 views (last 30 days)
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 Comments
Bruno Luong
Bruno Luong on 6 Aug 2021
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.

Sign in to comment.

Answers (1)

Matt J
Matt J on 6 Aug 2021
Edited: Matt J on 6 Aug 2021
(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.

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!