Terminate loop when condition is not met when save new file

1 Ansicht (letzte 30 Tage)
AIA56
AIA56 am 27 Apr. 2023
Kommentiert: AIA56 am 28 Apr. 2023
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

Akzeptierte Antwort

Adithya
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!
  1 Kommentar
AIA56
AIA56 am 28 Apr. 2023
This statement does, in fact, break the loop. Thank you incredibly much! Have a wonderful day!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

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!

Translated by