我对Matlab非常陌生,我试图尝试制作一个简单的迭代脚本。 基本上我想做的就是剧情:
1*sin(x)
2*sin(x)
3*sin(x)
...
4*sin(x)
这是我写的程序:
function test1
x=1:0.1:10;
for k=1:1:5;
y=k*sin(x);
plot(x,y);
end % /for-loop
end % /test1
但是,它只绘制y = 5 * sin(x)或最后一个数字是......
有什么想法吗?
谢谢! 阿米特
答案 0 :(得分:7)
您需要使用命令hold on
来确保每次绘制新内容时都不会删除绘图。
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.
修改强>
您也可以在没有循环的情况下执行此操作,并根据@Ofri的建议绘制2D数组:
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)
答案 1 :(得分:4)
另一种选择是使用绘图可以接受矩阵的事实,并将它们视为几行来绘制在一起。
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