/edit:循环不会变慢。我没有正确把握时间。见拉斯曼的回答。
我为一个有点长且复杂的函数循环了 3 个参数,我注意到两件我不明白的事情:
end
的 for
语句需要相当长的时间。 考虑以下示例(我知道这很容易被矢量化,但据我所知,我调用的函数不能):
function stuff = doSomething( x, y, z )
stuff.one = x+y+z;
stuff.two = x-y-z;
end
以及我如何执行该功能
n = 50;
i = 0;
currenttoc = 0;
output = zeros(n^3,4);
tic
for x = 1:n
for y = 1:n
for z = 1:n
i = i + 1;
output(i,1) = x;
output(i,2) = y;
output(i,3) = z;
stuff = doSomething(x,y,z);
output(i,4) = stuff.one;
if mod(i,1e4) == 0 % only for demonstration, not in final script
currenttoc = toc - currenttoc;
fprintf(1,'time for last 10000 iterations: %f \n',currenttoc)
end
end
end
end
我怎样才能加快速度?为什么每次迭代都比前一次花费更长的时间?我很确定这是可怕的编程,很抱歉。
最佳答案
因此,当我将 if 语句替换为:
if mod(i,1e4) == 0 % only for demonstration, not in final script
fprintf(1,'time for last 10000 iterations: %f \n',toc); tic;
end
我认为对 toc 的操作可能导致问题
关于MATLAB:嵌套的 for 循环每次连续迭代需要更长的时间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15078021/