0

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?

0

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.