对于完整矩阵:
您可以使用bsxfun 和shiftdim:
C = bsxfun(@times, A, shiftdim(B,-1))
解释:让A 的大小为 M x N,B 的大小为 N x P。应用 shiftdim(B,-1) 会得到一个 1 x N x P 的数组。 bsxfun 沿第三维隐式复制 A 并沿第一维复制 shiftdim(B,-1) 以计算所需的元素乘积。
另一种可能性,通常是less efficient 而不是bsxfun,是使用repmat 沿所需维度明确重复数组:
C = repmat(A, [1 1 size(B,2)]) .* repmat(shiftdim(B,-1), [size(A,1) 1 1])
对于稀疏矩阵:
结果不能是稀疏的,因为不支持稀疏的 ND 数组。但是您可以使用 linear indexing 对稀疏的 A 和 B 进行计算:
ind1 = repmat(1:numel(A),1,size(B,2));
ind2 = repmat(1:numel(B),size(A,1),1);
ind2 = ind2(:).';
C = NaN([size(A,1),size(A,2),size(B,2)]); %// preallocate with appropriate shape
C(:) = full(A(ind1).*B(ind2)); %// need to use full if C is to be 3D