Multiply a 3D matrix with a 2D matrix

前端 未结 10 1266
盖世英雄少女心
盖世英雄少女心 2020-11-28 09:29

Suppose I have an AxBxC matrix X and a BxD matrix Y.

Is there a non-loop method by which I can multiply

10条回答
  •  渐次进展
    2020-11-28 09:53

    You can do this in one line using the functions NUM2CELL to break the matrix X into a cell array and CELLFUN to operate across the cells:

    Z = cellfun(@(x) x*Y,num2cell(X,[1 2]),'UniformOutput',false);
    

    The result Z is a 1-by-C cell array where each cell contains an A-by-D matrix. If you want Z to be an A-by-D-by-C matrix, you can use the CAT function:

    Z = cat(3,Z{:});
    



    NOTE: My old solution used MAT2CELL instead of NUM2CELL, which wasn't as succinct:

    [A,B,C] = size(X);
    Z = cellfun(@(x) x*Y,mat2cell(X,A,B,ones(1,C)),'UniformOutput',false);
    

提交回复
热议问题