Terminate loop when condition is not met when save new file
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Hello, I attempted to save a file every 18 days (by moving window) using a 'for' loop. However, Matlab continues to save new files when the condition is not met, how should the loop be terminated in 'for' loop? I tried using the 'break' condition, but it didn't work. The loop code is as follows:
for i = mjd(1) : mjd(end)
hp2 = mjd_table(mjd_table(:,1) >= i & mjd_table(:,1) <= i+18,:); %sliding over 18 days
name = sprintf('%d.txt',i+18); %rename over 18 days moving windows
writematrix(num2str((hp2),'%.6f'),name);
end
0 Kommentare
Akzeptierte Antwort
Adithya
am 27 Apr. 2023
It seems that the loop in your code is running continuously because you have not included a condition to check whether the current time window is greater than the end time of your data. To terminate the loop, you can add a check for this condition inside the loop using an if statement.
For example, you can modify your loop as follows:
for i = mjd(1) : mjd(end)
hp2 = mjd_table(mjd_table(:,1) >= i & mjd_table(:,1) <= i+18,:); %sliding over 18 days
name = sprintf('%d.txt',i+18); %rename over 18 days moving windows
writematrix(num2str((hp2),'%.6f'),name);
if i+18 >= mjd(end)
break; % exit the loop if the current time window is greater than the end time
end
end
In this modified code, the if statement checks whether the current time window (i+18) is greater than or equal to the end time of your data (mjd(end)). If this condition is met, the loop is terminated using the break statement.
I hope this helps!
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!