How to plot two lines in a looped subplot in matlab?

10 views (last 30 days)
I plotted 5 graphs with a loop in MATLAB. Now, I want to add a further line only to the third plot. However, when I try to do it, it adds the additional line to every subplot.
What I have is this:
lines = rand([30 5])
line2 = rand([30 1])
K =5
for j = 1:k
subplot(3, 2, j);
plot(lines(:,j), 'LineWidth',1,'Color', [0 0 0.5]);
hold on
plot(line2, 'LineWidth',1,'Color', [0 0 0.5], 'LineStyle','b--o')
yline(0, '-')
end
Can anyone help me out?
Thanks!

Accepted Answer

Star Strider
Star Strider on 30 May 2020
Add an if block in the loop:
lines = rand([30 5]);
line2 = rand([30 1]);
k = 5;
for j = 1:k
subplot(3, 2, j);
plot(lines(:,j), 'LineWidth',1,'Color', [0 0 0.5]);
hold on
if j == 3
plot(line2, 'LineWidth',1,'Color', [0 0 0.5], 'LineStyle','-.')
end
yline(0, '-')
end
.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!