Search code examples
matlabmatrix-multiplicationcell-array

Matlab: Matrix multiplication of many matrices in cell arrays


I have a cell array size 1x200x201, in each cell is 2x2 matrix. I need to multiply the matrices in a way that I would get resulting matrix: 2x2x201. Which means: Cell_M{1,1,1}* Cell_M{1,2,1}*Cell_M{1,3,1}*... and so on up to 200, and the same up to 201 ( Cell_M{1,1,2}* Cell_M{1,2,2}*Cell_M{1,3,2}*... ). Cell arrays is just a way for handling the data. Is any effective way to do this multiplications?


Solution

  • Floating-point matrix multiplication is not associative in general, so A*B*C*D is ambiguous. In this code I assume you are looking for ((A*B)*C)*D

    d=size(Cell_M); 
    P = cell(d(1), 1, d(3)); 
    P(:)={eye(2)}; 
    for k=1:d(2), 
        P = cellfun(@mtimes, P(:,1,:), Cell_M(:,k,:), 'UniformOutput', false); 
    end
    P = squeeze(P);
    

    Now P will be a cell array of 201 elements where each element is a 2-by-2 matrix.