I'm very very new to Matlab and I tried to attempt at making a simple iteration script. Basically all I wanted to do was plot:
1*sin(x)
2*sin(x)
3*sin(x)
...
4*sin(x)
And this is the program that I wrote:
function test1
x=1:0.1:10;
for k=1:1:5;
y=k*sin(x);
plot(x,y);
end % /for-loop
end % /test1
However, it only plots y=5*sin(x) or whatever the last number is...
Any ideas?
Thanks! Amit
You need to use the command hold on
to make sure that the plot doesn't get erased each time you plot something new.
function test1
figure %# create a figure
hold on %# make sure the plot isn't overwritten
x=1:0.1:10;
%# if you want to use multiple colors
nPlots = 5; %# define n here so that you need to change it only once
color = hsv(nPlots); %# define a colormap
for k=1:nPlots; %# default step size is 1
y=k*sin(x);
plot(x,y,'Color',color(k,:));
end % /for-loop
end % /test1 - not necessary, btw.
EDIT
You can also do this without a loop, and plot a 2D array, as suggested by @Ofri:
function test1
figure
x = 1:0.1:10;
k = 1:5;
%# create the array to plot using a bit of linear algebra
plotData = sin(x)' * k; %'# every column is one k
plot(x,plotData)
Another option would be to use the fact the plot can accept matrices, and treats them as several lines to plot together.
function test1
figure %# create a figure
x=1:0.1:10;
for k=1:1:5;
y(k,:)=k*sin(x); %# save the results in y, growing it by a row each iteration.
end %# for-loop
plot(x,y); %# plot all the lines together.
end %# test1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With