在Matlab中向嵌套for循环中矢量化更高维 [英] Vectorizing ther higher dimensions in nested for loop in Matlab

查看:240
本文介绍了在Matlab中向嵌套for循环中矢量化更高维的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个5D矩阵 A ,我需要乘以一个向量的3-5维。例如,请参阅以下示例代码:

  A = rand(50,50,10,8,6); 
B = rand(10,1);
C = rand(8,1);
D = rand(6,1); (A,3)
对于j = 1:大小(A,4)
对于K = 1:大小(A,5)$

(i,j)* B(i)* C(j)* D(K); b(b)
end
end
end

不知有没有更好的\矢量化\更快的方法来做到这一点?

解决方案

首先,作为一个注释,这些天在Matlab中,用JIT编译,矢量化的代码不一定更快/更好。对于大问题,特别是内存使用可能会导致性能问题。



然而,这是一个向量化的解决方案,它看起来与您的代码具有相同的结果:

  A = rand(3,4,5,6,7); 
B = rand(5,1);
C = rand(6,1);
D = rand(7,1);

s = size(A);
[b,c,d] = ndgrid(B,C,D);
F = b。* c。* d;
G =零(1,1,prod(s(3:5)));
G(1,1,:)= F(:);
A = reshape(A,s(1),s(2),[]);
A = bsxfun(@ times,A,G);
A =重塑(A,s);

编辑:备用解决方案:

  A = bsxfun(@ times,A,permute(B,[2 3 1])); 
A = bsxfun(@ times,A,permute(C,[2 3 4 1]));
A = bsxfun(@ times,A,permute(D,[2 3 4 5 1]));


I have a 5D matrix A, and I need to multiply the 3rd-5th dimensions with a vector. For example, see the following sample code:

A=rand(50,50,10,8,6);
B=rand(10,1);
C=rand(8,1);
D=rand(6,1);

for i=1:size(A,3)
    for j=1:size(A,4)
        for K=1:size(A,5)
            A(:,:,i,j,K)=A(:,:,i,j,K)*B(i)*C(j)*D(K);
        end
    end
end

I wonder if there's a better \ vectorized \ faster way to do this?

解决方案

Firstly, as a note, these days in Matlab, with JIT compilation, vectorised code is not necessarily faster/better. For big problems the memory usage in particular can cause performance issues.

Nevertheless, here is a vectorised solution that seems to give the same results as your code:

A=rand(3,4,5,6,7);
B=rand(5,1);
C=rand(6,1);
D=rand(7,1);   

s=size(A);
[b,c,d]=ndgrid(B,C,D);
F=b.*c.*d;
G=zeros(1,1,prod(s(3:5)));
G(1,1,:)=F(:);
A=reshape(A,s(1),s(2),[]);
A=bsxfun(@times,A,G);
A=reshape(A,s);

EDIT: An alternate solution:

A=bsxfun(@times,A,permute(B,[2 3 1]));
A=bsxfun(@times,A,permute(C,[2 3 4 1]));
A=bsxfun(@times,A,permute(D,[2 3 4 5 1]));

这篇关于在Matlab中向嵌套for循环中矢量化更高维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆