user1943029
user1943029

Reputation: 79

MATLAB: plot in a loop

I've tried to do plot inside of a loop and it prints only the last plot.

How can i fix it?

I've tried to use hold on and drawnow after the plot definition but it didn't work.

This is my code:

for t=1:5
  alive = Game(World , Generations, speed);
  plot(hplot2,1:Generations,alive);
end

Upvotes: 1

Views: 207

Answers (5)

Shai
Shai

Reputation: 114786

If the function Game(World , Generations, speed) is a deterministic function - it gives the same output for every t. Therefore, every plot commands has exactly the same output and you cannot distinguish the first from the last plot.

Try plot a random series at each iteration (as in answer of shoelzer) and see if you see all 5 plots.

Additionally, you might want to use hold all instead of hold on: this way each plot will get a different color from the colormap.

Upvotes: 0

zina
zina

Reputation: 144

you can also use figure(t) to have 5 different figures.

Upvotes: 1

Karthik V
Karthik V

Reputation: 1897

Since you are already passing the axes handle to plot, you only need to put something like pause(0.1) inside the loop, and your original source will work.

Upvotes: 1

Pegasaurus
Pegasaurus

Reputation: 165

Sticking in a "figure" has always worked for me.

for t=1:5
    alive = Game(World , Generations, speed);
    figure;
    plot(hplot2,1:Generations,alive);
end

Upvotes: 2

shoelzer
shoelzer

Reputation: 10708

hold on should work. Try this:

figure
hplot2=gca;
hold on
for t=1:5
    alive = rand(1,Generations);
    plot(hplot2,1:Generations,alive);
end

Upvotes: 2

Related Questions