tags:

views:

56

answers:

2

Hi all,

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

+7  A: 

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)
Jonas
Worked! Thank you so much, genius
Amit
@Amit: Glad it worked fine. I've expanded the solution a bit.
Jonas
+4  A: 

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
Ofri Raviv
Great suggestion! תודה!!
Amit
This way is almost favorable because it alternates the colors of the lines as well! simply wonderful.
Amit
על לא דבר. if you want to manually set the colors in a plot, you can add a third parameter plot(x,y,color). color should be 'r' for red, 'b' for blue, etc. so you can add this feature to Jonas' solution by defining an array of colors col = ['r','g','b','c','m'] and then add col(k) as a third parameter to the plot.
Ofri Raviv
very clever, great idea!
Amit
@Ofri: +1 for great points. I incorporated this into my solution as well, using a colormap instead. Also, I stole and adapted your idea of plotting an array.
Jonas

related questions