Search code examples
matlabmultidimensional-arraycell-arraymultiplication

MATLAB: Multiply 2D matrix with 3D matrix within cell arrays


I have a constant 2D double matrix mat1. I also have a 2D cell array mat2 where every cell contains a 2D or 3D double matrix. These double matrices have the same number of rows and columns as mat1. I need to dot multiply (.*) mat1 with every slice of each double matrix within mat2. The result needs to be another cell array results with the same size as mat2, whereby the contatining double matrices must equal the double matrices of mat2 in terms of size.

Here's my code to generate mat1 and mat2 for illustrating purposes. I am struggling at the point where the multiplication should take place.

rowCells = 5;
colCells = 3;
rowTimeSeries = 300;
colTimeSeries = 5;
slices = [1;10];

% Create 2D double matrix
mat1 = rand(rowTimeSeries, colTimeSeries);

% Create 2D cell matrix comprisiong 2D and/or 3D double matrices
mat2 = cell(rowCells,colCells);

for c = 1:colCells
    for r = 1:rowCells
        slice = randsample(slices, 1, true);
        mat2{r,c} = rand(rowTimeSeries, colTimeSeries, slice);
    end
end

% Multiply (.*) mat1 with mat2 (every slice)

results = cell(rowCells,colCells);

for c = 1:colCells
    for r = 1:rowCells
        results{r,c} = ... % I am struggling here!!!
    end
end

Solution

  • You could use bsxfun to remove the need for your custom function multiply2D3D, it works in a similar way! Updated code:

    results = cell(rowCells,colCells);
    for c = 1:colCells
        for r = 1:rowCells
            results{r,c} = bsxfun(@times, mat1, mat2{r,c});
        end
    end
    

    This will work for 2D and 3D matrices where the number of rows and cols is the same in each of your "slices", so it should work in your case.


    You also don't need to loop over the rows and the columns of your cell array separately. This loop has the same number of iterations, but it is one loop not two, so the code is a little more streamlined:

    results = cell(size(mat2));
    for n = 1:numel(mat2)   % Loop over every element of mat2. numel(mat2) = rowCells*colCells
        results{n} = bsxfun(@times, mat1, mat2{n});
    end