Clear Filters
Clear Filters

Terminate loop when condition is not met when save new file

1 view (last 30 days)
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

Accepted Answer

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

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!