Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attempting to create iterations with MATLAB (beginner)

Tags:

plot

matlab

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

like image 312
Amit Avatar asked Dec 22 '22 23:12

Amit


2 Answers

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)
like image 61
Jonas Avatar answered Jan 06 '23 19:01

Jonas


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
like image 20
Ofri Raviv Avatar answered Jan 06 '23 19:01

Ofri Raviv