MATLAB缩放的repmat

时间:2016-08-29 03:48:59

标签: performance matlab

有没有一种简单的方法可以在matlab中使用缩放的repmat?

这个想法是,给定矩阵AB

result = [A*B(1, 1) A*B(1, 2) A*B(1, 3) ... 

          A*B(1, n); A*B(2, 1)...];

现在我通过使用permute和reshape来实现这一点,但是置换操作是我脚本时间的90%。

2 个答案:

答案 0 :(得分:3)

我认为您正在寻找kron

result = kron(B, A);

答案 1 :(得分:2)

您可能正在执行元素乘法,从而产生一个巨大的数组,然后进行置换。现在,大型阵列上的permute将导致大量数据传输,这将无效。所以,我猜你正在做这些事情:

reshape(permute(bsxfun(@times,A,permute(B,[3,4,1,2])),[1,3,2,4]),N,[]) 
           ^ (kills performance)    

替代方法是在permuteA上执行B之前,在输入数组之间执行元素乘法运算,这样最终我们只需要reshape。在相对AB上进行置换应该更有效率。

因此,一个有效的解决方案是 -

n = size(A,1)*size(B,1);
out = reshape(bsxfun(@times,permute(A,[1,3,2]),permute(B,[3,1,4,2])),n,[]);

运行时测试

让我们来看看两种方法来验证我们的性能改进,并且还包括@ Shai的帖子中建议的基于kron的方法,这似乎是一个干净的解决方案 -

% Max sized input arrays that my system could handle
A = randi(9,70,70);
B = randi(9,70,70);

disp('-------------- With permute on A and B and finally reshaping')
tic
n = size(A,1)*size(B,1);
out0 = reshape(bsxfun(@times,permute(A,[1,3,2]),permute(B,[3,1,4,2])),n,[]);
toc, clear out0 n

disp('-------------- With permute on elementwise result')
tic
n = size(A,1)*size(B,1);
out1 = reshape(permute(bsxfun(@times,A,permute(B,[3,4,1,2])),[1,3,2,4]),n,[]);
toc, clear out1 n

disp('-------------- With kron from @Shai post')
tic,
result1 = kron(B, A);
toc

计时 -

-------------- With permute on A and B and finally reshaping
Elapsed time is 0.161598 seconds.
-------------- With permute on elementwise result
Elapsed time is 0.413746 seconds.
-------------- With kron from @Shai post
Elapsed time is 0.612825 seconds.