How do I create many different plots, on different figures, quickly and neatly

2 views (last 30 days)
So I need 10 plots, all of them on their own figure. They all have the same x values, but the only thing that is different is the y value. Also I want to add LLSQ line fit to it. Is there a way I can create something neat that will make all those differnt plots without having to do the code below many times? Like can I do a loop where a new y value is put in place?
figure(1)
plot(x,y)
figure(2)
plot(x2,y2)
figure(3)
plot(x3,y3)

Accepted Answer

Ameer Hamza
Ameer Hamza on 7 Nov 2020
The first mistake was creating variable names like this: x, x2, x3. Such variable names make it extremely difficult to write compact code and are discouraged: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. It is better to create a cell array, and then you could easily use for-loop. For example, now you can do something like this
X = {x, x2, x3, x4, x5, x6, x7, x8, x9, x10};
Y = {y, y2, y3, y4, y5, y6, y7, y8, y9, y10};
for i = 1:numel(X)
figure(i)
plot(X{i}, Y{i})
end
  2 Comments
Nicholas Connolly
Nicholas Connolly on 7 Nov 2020
This worked great! Is there a way that I can make different titles for each of the figures?
Ameer Hamza
Ameer Hamza on 8 Nov 2020
You can add the titles inside for-loop
X = {x, x2, x3, x4, x5, x6, x7, x8, x9, x10};
Y = {y, y2, y3, y4, y5, y6, y7, y8, y9, y10};
titles = {'title1', 'title2', ...}
for i = 1:numel(X)
figure(i)
plot(X{i}, Y{i})
title(titles{i})
end

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!