首页 文章

MATLAB缩放的repmat

提问于
浏览
1

有没有一种简单的方法在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 回答

  • 3

    我想你正在寻找kron

    result = kron(B, A);
    
  • 2

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

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

    另一种方法是在输入数组之间执行元素乘法之前在 AB 上执行 permute ,这样最终我们只需要 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,[]);
    

    Runtime test

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

    % 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.
    

相关问题