While running simulation, plot each curve with a different color

1 view (last 30 days)
Hi all, I saw many thread on the same question but I guess I don't understand how it works. I want to get different possibilities for the phi matrix so I'm running simul and want a plot with all the curves with a different color. I don't know if the problem come from where I put the plot and hold on but would really appreciate some help ! This is a MWE.
{
nb=[];
total=[];
con=[];
nbcon=[];
simul=[];
hold all
for simul=1:5
phi=zeros(4,4);
for nbIter=1:30
Nel = numel(phi);
Rindices = randperm(Nel);
N10 = floor(Nel/10);
phi(Rindices(1:N10)) = 1
nbcon=sum(sum(phi))
nb=sum(sum(phi))*rand(1);
con=[con; nb, nbcon];
end
plot(con(:,2),con(:,1),'color', rand(1,3))
end
hold off

Accepted Answer

Geoff Hayes
Geoff Hayes on 22 Jul 2014
The problem is that the code is plotting all the data at each iteration, including that which was plotted at previous iterations. So all points are being overwritten with the new random colour.
Just reset con to the empty matrix on each iteration of the outer for loop, that way the code doesn't hang on to the legacy data from previous iterations
for simul=1:5
phi=zeros(4,4);
con = []; % new line of code to add
% etc.
Try the above and see what happens!
  3 Comments
Geoff Hayes
Geoff Hayes on 22 Jul 2014
Just create a figure and add hold on after it to retain the current graph when adding new graphs. Replace the
hold all
with
figure;
hold on;
Joseph Cheng
Joseph Cheng on 22 Jul 2014
Perhaps use a colormap to get the color to get some distinct colors to plot.
Linecolor = hsv(numberoflines);
in the held plot
plot(con(iteration,2),con(iteration,1),'color', Linecolor(iteration,:))

Sign in to comment.

More Answers (1)

hibou
hibou on 23 Jul 2014
Edited: hibou on 23 Jul 2014
Geoff and Joseph, thanks for your help ! I really couldn't get where and when use the hold on command. The answer by Geoff Hayes pointed me that I had to delete the con matrix at the outer loop and Joseph Cheng helped me set up the plot colors. And here is a simple way for different color curve:
clc
close all
clear all
nb=[];
total=[];
con=[];
nbcon=[];
simul=[];
for simul=1:5
phi=zeros(4,4);
for nbIter=1:30
Nel = numel(phi);
Rindices = randperm(Nel);
N10 = floor(Nel/10);
phi(Rindices(1:N10)) = 1
nbcon=sum(sum(phi))
nb=sum(sum(phi))*rand(1);
con=[con; nb, nbcon]
end
hold on
Linecolor = hsv(5);
plot(con(:,2),con(:,1),'color', Linecolor(simul,:))
con=[];
end
hold off
Thanks a lot !!

Categories

Find more on Line Plots 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!