编辑(基准测试):由于已经提出了多种解决方案(包括下面的我的解决方案),这里提供一些粗略的基准测试结果来比较不同的解决方案,使用较大的数组:
a=1:10;
N=1000; timers=zeros(N,6);
for ii=1:N; C=rand(400);
tic; out = repmat(C,[1,1,numel(a)]).*reshape(repelem(a,size(C,1),size(C,2)),[size(C),numel(a)]); timers(ii,1)=toc;
tic; out = bsxfun(@times,C,reshape(a,1,1,[])); timers(ii,2)=toc;
tic; out = reshape(C(:)*a, size(C,1), size(C,2), numel(a)); timers(ii,3)=toc;
tic; out = bsxfun(@mtimes,C,permute(a,[3,1,2])); timers(ii,4)=toc;
tic; out = reshape(bsxfun(@mtimes, C(:), a(:).'), [size(C),numel(a)] ); timers(ii,5)=toc;
tic; out = reshape(kron(a,C),[size(C),numel(a)]); timers(ii,6)=toc;
end;
mean(timers)
ans =
0.0080863 0.0032406 0.0041718 0.015166 0.0074462 0.0033051
建议使用 @hbaderts 的解决方案最快,其次是 @Adiel's,然后是@Luis Mendo's,@thewaywewalk's(1),然后是我的,最后是@thewaywewalk's (2)。
我的解决方案:
另一种选择是使用repmat
和 reshape
(无需使用bsxfun
):
out = repmat(C,[1,1,numel(a)]).*reshape(repelem(a,size(C,1),size(C,2)),[size(C),numel(a)])
out(:,:,1) =
1 2 3
4 5 6
7 8 9
out(:,:,2) =
2 4 6
8 10 12
14 16 18
这是两个数组的逐元素乘法。 第一个数组是您原始矩阵 C
在第三维度上重复了 numel(a)
次:
repmat(C,[1,1,numel(a)])
ans(:,:,1) =
1 2 3
4 5 6
7 8 9
ans(:,:,2) =
1 2 3
4 5 6
7 8 9
第二个的大小与第一个相同,每个切片都包含
a
中对应的元素:
reshape(repelem(a,size(C,1),size(C,2)),[size(C),numel(a)])
ans(:,:,1) =
1 1 1
1 1 1
1 1 1
ans(:,:,2) =
2 2 2
2 2 2
2 2 2