[英]How can I vectorize these nested for-loops in Matlab?
I have a piece of code here I need to streamline as it is greatly increasing the runtime of my script: 我这里需要简化一些代码,因为这大大增加了脚本的运行时间:
size=300;
resultLength = (size+1)^3;
freqResult=zeros(1, resultLength);
inc=1;
for i=0:size,
for j=0:size,
for k=0:size,
freqResult(inc)=(c/2)*sqrt((i/L)^2+(j/W)^2+(k/H)^2);
inc=inc+1;
end
end
end
c, L, W, and H are all constants. c,L,W和H都是常数。 As the size input gets over about 400, the runtime is too long to wait for, and I can watch my disk space draining by the gigabyte. 当输入的大小超过400左右时,运行时就太长了,无法等待,我可以看到磁盘空间正在以GB的形式耗尽。 Any advice? 有什么建议吗?
Thanks! 谢谢!
What about this: 那这个呢:
[kT, jT, iT] = ind2sub([size+1, size+1, size+1], [1:(size+1)^3]);
for indx = 1:numel(iT)
i = iT(indx) - 1;
j = jT(indx) - 1;
k = kT(indx) - 1;
freqResult1(indx) = (c/2)*sqrt((i/L)^2+(j/W)^2+(k/H)^2);
end
On my PC, for size = 400, version with 3 loops takes 136s and this one takes 19s. 在我的PC上,对于大小= 400,带有3个循环的版本需要136秒,而这个需要19秒。
For more "matlaby" way u could also even do as follows: 对于更多的“ matlaby”方式,您甚至可以执行以下操作:
[kT, jT, iT] = ind2sub([size+1, size+1, size+1], [1:(size+1)^3]);
func = @(i, j, k) (c/2)*sqrt((i/L)^2+(j/W)^2+(k/H)^2);
freqResult2 = arrayfun(func, iT-1, jT-1, kT-1);
But for some reason, this is slower then the above version. 但是由于某种原因,它比上面的版本慢。
A faster solution can be (based on Marcin's answer): 更快的解决方案可以是(基于Marcin的答案):
[k, j, i] = ind2sub([size+1, size+1, size+1], [1:(size+1)^3]);
freqResult = (c/2)*sqrt(((i-1)/L).^2+((j-1)/W).^2+((k-1)/H).^2);
It takes about 5 seconds to run on my PC for size = 300
在我的PC上运行, size = 300
大约需要5秒钟
The following is even faster (but it doesn't look very good): 以下代码甚至更快(但看起来不太好):
k = repmat(0:size,[1 (size+1)^2]);
j = repmat(kron(0:size, ones(1,size+1)),[1 (size+1)]);
i = kron(0:size, ones(1,(size+1)^2));
freqResult = (c/2)*sqrt((i/L).^2+(j/W).^2+(k/H).^2);
which takes ~3.5s for size = 300
对于size = 300
,大约需要3.5秒
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.