Terminate loop when condition is not met when save new file

1 次查看(过去 30 天)
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

采纳的回答

Adithya
Adithya 2023-4-27
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!

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by