How to create one plot with multiple lines in a for loop?

258 views (last 30 days)
I have been trying to create a plot, with an unknown number of lines. Each should be on the same graph, and a different colour. However, I am only getting one line on my graph.
This is my code currently:
y = cell(numFiles,1) ;
x = [30:10:100]
hold on
for k = 1:numFiles
%Code that generates data
y{k} = [h g f e d c b a ]
plot(x,y{k}, 'Color', [rand,rand,rand])
title('SNR / Index')
hold off
What am I doing wrong? Thank you!

Accepted Answer

Jan on 27 May 2021
x = 30:10:100;
% axes('NextPlot', 'add'); % Same as: hold on
hold on
for k = 1:8
y{k} = rand(size(x));
plot(x, y{k}, 'Color', rand(1, 3))
You see, it works with hold('on') or with creating the axes explicitly also.
Are you sure, that this is your code and there is no cla anywhere?
Jan on 28 May 2021
The debugger is the best friend of the programmer.

Sign in to comment.

More Answers (0)


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!