Reputation: 189
Working on a review exercise from Van Loan's Introduction to Scientific Computation. It's P1.2.4 in case anyone wants to know. I can't figure out why my code produces a single plot.
x=linspace(0,2*pi, 30);
for k=1:5
plot(x, sin(k*x));
end
It seems like I need to do
plot(x, sin(x), x, sin(2*x), x, sin(3*x)....)
But this seems to be an excessive amount of hand coding, is there a more elegant way?
Upvotes: 0
Views: 727
Reputation: 8091
Do you want 5 separate plots? Then use something like
for k=1:5
figure
plot(x, sin(k*x));
end
Or all plots in one figure? In this case use "hold"
hold on
for k=1:5
plot(x, sin(k*x));
end
hold off
or the third method: use plot with X and Y as matrices
Upvotes: 1
Reputation: 9075
You can use hold on
in a for
loop. You also need to use the 'Color'
field in plot
to make the plots of distinct color. At each iteration, just choose a triplet of random numbers between 0 to 1.
x=linspace(0,2*pi, 30);
for k=1:5
plot(x, sin(k*x),'Color',rand(1,3));hold on;
end
hold off;
Upvotes: 1