1

我在这里有一段代码需要简化,因为它大大增加了我的脚本的运行时间:

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 和 H 都是常数。随着大小输入超过 400,运行时间太长而无法等待,我可以看到我的磁盘空间以千兆字节为单位耗尽。有什么建议吗?

谢谢!

4

2 回答 2

0

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.

For more "matlaby" way u could also even do as follows:

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

于 2013-08-22T01:53:34.743 回答
0

更快的解决方案可以是(基于 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); 

在我的电脑上运行大约需要 5 秒size = 300

以下甚至更快(但看起来不太好):

   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);

大约需要 3.5 秒size = 300

于 2013-08-22T16:44:21.983 回答