问题描述
假设我有一个 AxBxC 矩阵X
和一个 BxD 矩阵Y
.
Suppose I have an AxBxC matrix X
and a BxD matrix Y
.
是否存在一种非循环方法,我可以通过该方法将每个 C AxB 矩阵与Y
相乘?
Is there a non-loop method by which I can multiply each of the C AxB matrices with Y
?
推荐答案
您可以使用 NUM2CELL 将矩阵X
分解为单元格数组和 CELLFUN 以便在所有单元中进行操作:
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);
结果Z
是一个 1-by-C 单元格数组,其中每个单元格都包含一个 A-by-D 矩阵.如果希望Z
成为 A-D-D-C 矩阵,则可以使用 CAT 函数:
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{:});
注意::我的旧解决方案使用了 MAT2CELL 而不是 NUM2CELL ,不那么简洁:
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);
这篇关于将3D矩阵与2D矩阵相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!