For loop slows down on row 25 of 3D matrix and does not advance and original speed. What may be the issue?
1 次查看(过去 30 天)
显示 更早的评论
Hi everyone,
I am using the following code to calculate a given parameter. I have included a progress bar for testing purposes and I noted that it always sticks at 19%. Upon further snooping around, I realize the for loop does not stop but greatly slows down after 19% even though the progress bar says only 2 min 33 secs left.
I am not running out of memory (checking with top command in the terminal) and there seems to be nothing odd about the data/anything different from surrounding data.
testcase1 = single(zeros(length(lon),length(lat),length(time)));
testcase2 = single(zeros(length(lon),length(lat),length(time)));
progressbar
for i = 1:length(lon);
for j = 1:length(lat);
for t = 1:length(time);
if C(i,j,t) >= -500 && C(i,j,t) <= -12
testcase1(i,j,t) = A(i,j,t)*(0.35*((-(B(i,j,t)/(K*C(i,j,t))))^(2/3)) + (2 -(10/B(i,j,t))))^(1/2);
else
testcase2(i,j,t) = 2*A(i,j,t)*((1 -(10/B(i,j,t)))^(1/2));
end
end
end
progressbar(i/121) % Update progress bar
end
Any ideas why this would stick/slow down here?
0 个评论
采纳的回答
Guillaume
2015-6-24
If that's the above code that you're running, I don't see any reason for it to hang.
However, there are many ways to speed it up. For a start, passing the output class (single) to zeros instead of generating a double matrix and then converting it to single would be faster:
testcase1 = zeros(numel(lon), numel(lat), numel(time), 'single');
testcase2 = zeros(numel(lon), numel(lat), numel(time), 'single');
Secondly, the loop is completely unnecessary (and is a performance killer). Use vectorised operations:
tf = C >= -500 & C <= -12;
testcase1(tf) = A(tf).*(0.35*((-(B(tf)./(K*C(tf)))).^(2/3)) + (2 -(10./B(tf)))).^(1/2);
testcase2(~tf) = 2*A(~tf).*((1 -(10./B(~tf))).^(1/2));
Just three lines!
6 个评论
Guillaume
2015-6-24
The vectorised version will either produces the whole output or nothing at all if it runs out of memory. There's no in between.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!