Speed Up the for loop

7 次查看(过去 30 天)
for j=1:120000
disp(j);
for i=1:7000000
disp(i);
if (strcmpi(x(i),y(j)))
if (T1(i)==W1(j) && DOY2(i)==W2(j))
if ((T6(i)-0.125<=W3(j))&&(W3(j)<=T6(i)+0.125))
fprintf(fileID,'%s \t %6.2f \t %6.2f \t %6.2f \t %6.2f \t %6.4f \t %6.4f\t %6.2f \t %6.2f \t %6.4f \t %6.4f\t %6.2f \t %6.2f \t %6.2f \t %6.2f',cell2mat(y(j)),T1(i),DOY2(i),T6(i),T7(i),T8(i),T9(i),T10(i),W1(j),W2(j),W3(j),W4(j),W5(j),W6(j),W7(j));
fprintf(fileID,'\n');
end
end
end
end
end
  1 个评论
Arun Kumar Singh
Arun Kumar Singh 2021-9-16
This loop has to be run for i=1:7000000 into another loop for j=1:120000 times, How to Speed up this loop ?

请先登录,再进行评论。

采纳的回答

Jan
Jan 2021-9-16
编辑:Jan 2021-9-16
Fmt1 = '%6.2f \t %6.4f \t %6.4f\t %6.2f \t %6.2f \t %6.2f \t %6.2f';
Fmt2 = '%s \t %6.2f \t %6.2f \t %6.2f \t %6.2f \t %6.4f \t %6.4f\t %6.2f \t %s\n';
fileID = fopen(FileName, 'W'); % Uppercase!
for j = 1:120000
W3u = W3(j) + 0.125;
W3l = W3(j) - 0.125;
% [EDITED] the {j} belongs to y, not to x:
m = strcmpi(x, y{j}) & T1 == W1(j) & DOY2 == W2(j) & ...
W3l <= T6 & T6 <= W3u;
WStr = sprintf(Fmt1, W1(j), W2(j), W3(j), W4(j), W5(j), W6(j), W7(j));
for i = 1:7000000
if m(i)
fprintf(fileID, Fmt2, ...
y{j}, T1(i), DOY2(i), T6(i), T7(i), T8(i), T9(i), T10(i), WStr);
end
end
end
fclose(fileID);
AS far as I understand, y and x are cell strings. Then cell2mat(y(j)) is a slow version of y{j} .
  13 个评论
Jan
Jan 2021-9-17
编辑:Jan 2021-9-17
Sorry, the interface of the forum does not let my type, what I want to. Code formatting should be easy and intuitive, but the editor in this forum is a mess.
Change the line " for i = find(m) " to " for i = find(m).' "
You know, that you can use the debugger to fix such problems also?

请先登录,再进行评论。

更多回答(1 个)

Bjorn Gustavsson
Bjorn Gustavsson 2021-9-16
A couple of suggestions:
0, check the time spent on different lines by running this script with smaller limits on j and i with the profiler running.
1, cut out the disp(i) and disp(j) entirely. In your version you'll have matlab printing some 8.4*10^11 numbers to the command-window. There's no way that your screen-pixels will survive that. (perhaps put something like:
if mod(j,1000)==0
fprintf('%d: %s\n',j,datestr(now,'HH:MM:SS'))
end
in to see that it turns over. You can modify the divisor to get more or less frequent updates
)
2, put the '\n' into the first fprintf call - should/might speed things up.
3, combine all conditions into one if-test, they are supposed to shortcut as soon as the TRUE/FALSE is determined - this might speed up or slow down, but ought to be worth a test.
4, instead of calling cell2mat in every fprintf-call do that separately first for all cells in y to create an array of strings, this might speed things up a bit.
HTH

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by