How do I only save my solution every x iterations in a for loop?
Afficher commentaires plus anciens
I'm solving a PDE and iterating in time in a for loop. However, I don't want to store the solution at every single time step. Instead I want to be able to define how many times the solution should be stored.
I've tried this:
incrementer = 2
for itimestep = itimestepvector
currentsolution = update_solution(state,currentsolution);
if (mod(itimestep,maxitimestep/numberoftimesIwantorecord) == 0)
solutions(:,incrementer) = currentsolution;
incrementer = incrementer + 1;
end
end
The problem is this code doesn't save the solution in time "numberoftimesIwantorecord" number of times and I understand why it doesn't. How do i make the solution record "numberoftimesIwantorecord" number of times?
Réponse acceptée
Plus de réponses (1)
Rik
le 17 Nov 2017
The problem is in the rounding. You can improve the robustness of your code by rounding maxitimestep/numberoftimesIwantorecord, but that still won't solve all cases.
maxitimestep=10;
for numberoftimesIwantorecord=1:10
recorded_with_round=sum(mod(1:maxitimestep,round(maxitimestep/numberoftimesIwantorecord))==0);
recorded_without_round=sum(mod(1:maxitimestep,(maxitimestep/numberoftimesIwantorecord))==0);
fprintf('%2.0f times requested, %2.0f times done (%2.0f times without round)\n',...
numberoftimesIwantorecord,recorded_with_round,recorded_without_round)
end
This results in
1 times requested, 1 times done ( 1 times without round)
2 times requested, 2 times done ( 2 times without round)
3 times requested, 3 times done ( 1 times without round)
4 times requested, 3 times done ( 2 times without round)
5 times requested, 5 times done ( 5 times without round)
6 times requested, 5 times done ( 2 times without round)
7 times requested, 10 times done ( 1 times without round)
8 times requested, 10 times done ( 2 times without round)
9 times requested, 10 times done ( 1 times without round)
10 times requested, 10 times done (10 times without round)
Catégories
En savoir plus sur Performance and Memory dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!