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

8 Ansichten (letzte 30 Tage)
Megan Ross
Megan Ross am 6 Aug. 2021
Bearbeitet: Matt J am 6 Aug. 2021
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 Kommentare
Bruno Luong
Bruno Luong am 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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Matt J
Matt J am 6 Aug. 2021
Bearbeitet: Matt J am 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.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by