将 5D 矩阵与 2D 矩阵相乘
我有一个 5D 矩阵 Cij(3,3,Nx,Ny,Nz),其中 Nx、Ny 和 Nz 作为输入给出。
我需要执行这样的操作:
for ikx=1:Nx,
for iky=1:Ny,
for ikz=1:Nz,
%Random simulation of fourier components
n=zeros((3),'double');
for j=1:9,
ncomponent=randn(2);
n(j)=complex(ncomponent(1),ncomponent(2));
%Calculation of H
H(:,ikx,iky,ikz)=dot(Cij(:,:,ikx,iky,ikz),n);
end;
end;
end;
end;
问题是增加 Nx,Ny,Nz 循环需要花费大量时间来计算 H 矩阵。
有人知道获得 H 矩阵的更快方法吗?
I have a 5D matrix Cij(3,3,Nx,Ny,Nz) where Nx,Ny and Nz are given as input.
I need to perform something like this:
for ikx=1:Nx,
for iky=1:Ny,
for ikz=1:Nz,
%Random simulation of fourier components
n=zeros((3),'double');
for j=1:9,
ncomponent=randn(2);
n(j)=complex(ncomponent(1),ncomponent(2));
%Calculation of H
H(:,ikx,iky,ikz)=dot(Cij(:,:,ikx,iky,ikz),n);
end;
end;
end;
end;
The problem is that increasing Nx,Ny,Nz the loop requires a real huge time to get the H matrix calculated.
Does anybody know any faster way to get H matrix?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先应该注意的是,在最里面的循环中,您执行点积 9 次,每次都会覆盖
H(:,ikx,iky,ikz)
。那没有意义。您只需在循环内填充n
的随机值,并计算H(:,ikx,iky,ikz)
一次 >在该循环之后。但是,所有循环都是不必要的,因为您可以利用函数 DOT 是矢量化的,可以处理 5 维数组(即,它将自动执行跨第一个非单一维度的点运算)。您所要做的就是使
n
成为一个 3×3×Nx-by-Ny-by-Nz 复数值矩阵。这两行应该给出与上面的代码相同的结果:函数 SQUEEZE 用于从
H
中删除单一维度,这将使其成为 3×Nx×Ny×Nz 矩阵。It should first be noted that within your inner-most loop you perform the dot product 9 times, overwriting
H(:,ikx,iky,ikz)
each time. There's no point to that. You should just fill in the random values forn
within the loop, and computeH(:,ikx,iky,ikz)
once after that loop.However, all the loops are unnecessary since you can take advantage of the fact that the function DOT is vectorized and can handle 5-D arrays (i.e. it will automatically perform the dot operation across the first non-singleton dimension). All you have to do is make
n
a 3-by-3-by-Nx-by-Ny-by-Nz matrix of complex values. These two lines should give you the same result as your code above:The function SQUEEZE is used to remove singleton dimensions from
H
, which will make it a 3-by-Nx-by-Ny-by-Nz matrix.您可以使用一些
reshape
(和permute
)来做到这一点如果您想要在n和C的每个元素之间进行矩阵乘法:
如果您想要在n和每个元素之间进行点积的C:
You can do that using some
reshape
(andpermute
)If you want a mtrix multiplication between n and each element of C:
If you want a dot product between n and each element of C: