登录论坛

查看完整版本 : 尝试使用MATLAB创建迭代(入门)


poster
2019-12-10, 20:48
我对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)或最后一个数字是...

有任何想法吗?

谢谢!阿米特



回答:

您需要使用命令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的 (https://stackoverflow.com/questions/3596498/attempting-to-create-iterations-with-matlab-beginner/3596530#3596530)建议绘制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)

更多&回答... (https://stackoverflow.com/questions/3596498)