Home > front end >  Matlab sequential multiplication 3D matrix
Matlab sequential multiplication 3D matrix

Time:12-30

I've got a NxNxM matrix and I want to multiply all of them in order to have an NxN matrix, like

A(:,:,1) * A(:,:,2) * A(:,:,3) * ... A(:,:,M)

Is there a function doing this? Or should I use a for cycle?

CodePudding user response:

Best I can think of, using plain Matlab code:

out = A(:,:,1);
for jj = 2:size(A,3)
    out = out*A(:,:,jj);
end

Alternatively, with the aid of the Symbolic Math Toolbox, the fold (help here) function comes to the rescue:

res = fold(@mtimes, squeeze( num2cell(A, [1,2]) ))

where num2cell with the additional parameter [1,2]converts the 3D matrix into a cell array containing the individual pages and squeeze gets rid of the singleton dimensions. @mtimes is the handle of the built-in function that takes care of the matrix multiplication.

I haven't checked, but I suspect the approach based on fold is going to be more memory intensive and overall slower than the plain for loop, as it involves a conversion to cell array. And it requires a toolbox, of course.

  • Related