# How to generate a for loop which saves a figure at a given interval?

1 view (last 30 days)
HC98 on 3 Dec 2018
Answered: Prem Kumar Tiwari on 12 Dec 2018
Hello,
I'm designing a piece of code which plots a contour of a field I called rho in the code. I am encountering some difficulty in implementing a for loop/ program which generates a contourf plot over a given interval up to the maximum time. I have a maximum time (t) of 500 seconds and a step (dt) of 0.1 seconds. I am attempting to generate a seperate contourf plot at intervals of 10% up to the max time.
My code is as follows:
for z=1:2
d=figure
hold on
contourf(rho)
saveas(d,sprintf('FIG%d.png',z));
end

Prem Kumar Tiwari on 12 Dec 2018
For Loops in Matlab - This is a good link to read and learn more about how "for" loops work in Matlab.
I have two quick suggestions for this:
1. What is being passed in the "countourf" function is not changing over different iterations of the loop. Hence all the figures will look same. In this case you're passing 'rho' to 'countourf' function which over various iterations of the loop is not changing. You will have to make some changes in the broader code, so that the place where value to 'rho' is being assigned can be brought inside the loop along with it's one level dependencies, in the current function/script, which are helping the variable 'rho' to receive value.
2. You would also like to change the 'for' loop declaration so that it starts from 0 and with 'dt' increments in each iteration runs until maximum time 't'. I strongly recommend to learn about 'for' loops from the link mentioned above. For your quick understanding please have a look at the following.
dt = 0.1;
t = 500;
for i = 0:dt:t
% code goes here
end
This loop starts from 0, and keeps running with 'dt' steps until 't' is hit (runs last time with value of 'i' is equal to 't').