Why does the for loop show the graph of the last plot?

Hi everyone.
My code is:
for i=46:52
plot(x,y1(:,i))
title("Title 1")
xlabel("xlabel1")
ylabel("ylabel1")
plot(x,y2(:,i))
title("Title 2")
xlabel("xlabel2")
ylabel("ylabel2")
end
Unrecognized function or variable 'x'.
Here x is a vector and y1, y2 are matrix. I intend to plot 14 different graphs of line (not in single figure, so didn't use hold on). But matlab executes only plot(x,y2(:,52)) and its title and labels. I would be grateful if someone could explain the reasoning.

 Akzeptierte Antwort

Matt J
Matt J am 30 Apr. 2024
Bearbeitet: Matt J am 30 Apr. 2024
Use figure() to open a new figure window for each plot (otherwise, each plot will overwrite the previous plot in that window).
for i=46:52
figure;
plot(x,y1(:,i))
title("Title 1")
xlabel("xlabel1")
ylabel("ylabel1")
figure;
plot(x,y2(:,i))
title("Title 2")
xlabel("xlabel2")
ylabel("ylabel2")
end

7 Kommentare

tiledlayout('flow')
for i=46:52
nexttile();
plot(x,y1(:,i))
title("Title 1")
xlabel("xlabel1")
ylabel("ylabel1")
nexttile();
plot(x,y2(:,i))
title("Title 2")
xlabel("xlabel2")
ylabel("ylabel2")
end
Thanks to both of you. Is it because of some property of for loop that all the plots are supposed to be in the same window one over another? Cause, as far as I understand, when we call plot function, it automatically creates a new window to plot the graph. (I might be wrong)
Matt J
Matt J am 1 Mai 2024
Bearbeitet: Matt J am 1 Mai 2024
Thanks to both of you.
You're welcome, but please Accept-click the answer if it resolves your question.
(I might be wrong)
I'm afraid that is wrong. As I said before, plot() does nothing to open a new plotting area for itself. It will use the current figure and axis, erasing anything that was there, unless you point it to a new figure/axis to use (or apply hold())..
But whenever I used plot function twice (outside of for loop) so far, they generated two different plots. Why is that?
for example,
plot(x,y1)
Unrecognized function or variable 'x'.
title("Title 1")
xlabel("xlabel1")
ylabel("ylabel1")
plot(x,y2)
title("Title 2")
xlabel("xlabel2")
ylabel("ylabel2")
this generates two figures
Using plot() multiple times produces separate figures in LiveScript -- but not if you are using the regular command window.
Jishan
Jishan am 1 Mai 2024
Bearbeitet: Jishan am 1 Mai 2024
I was using LiveScript in both cases.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Gefragt:

am 30 Apr. 2024

Bearbeitet:

am 1 Mai 2024

Community Treasure Hunt

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

Start Hunting!

Translated by