[关闭]
@joyphys 2015-10-03T08:41:28.000000Z 字数 1847 阅读 1629

第2讲:Matlab 遍程

Blog Todd讲Matlab


Matlab也可以编程,可存为以.m为后缀的文件,称为M文件。M文件有两种:函数和脚本。

函数程序

点击新建图标,在打开的窗口里输入如下内容:

  1. function y = myfunc (x)
  2. y = 2*x.^2 - 3*x + 1;

将文件保存为myfunc.m,保存在当前目录下。这个文件就可以直接在命令窗口使用了,用法如Matlab内置函数,如在命令窗口输入如下内容:

  1. >> x = -2:.1:2;
  2. >> y = myfunc(x);
  3. >> plot(x,y)

这里函数文件和命令窗口都用了变量x和y,这只是巧合,其实只有文件名才是重要的,函数调用的变量名不重要,比如完全可以把上述文件写为:

  1. function nonsense = yourfunc ( inputvector )
  2. nonsense = 2* inputvector .^2 - 3* inputvector + 1;

函数程序结构都类似此程序。函数程序基本要素为:

函数可以有多个输入,用逗号隔开,如:

  1. function y = myfunc2d (x,p)
  2. y = 2*x.^p - 3*x + 1;

函数可以有多个输出,放在一个向量里面,如:

  1. function [x2 x3 x4] = mypowers (x)
  2. x2 = x .^2;
  3. x3 = x .^3;
  4. x4 = x .^4;

将此文件保存为mypowers.m,在命令窗口里如下命令画图:

  1. >> x = -1:.1:1
  2. >> [x2 x3 x4] = mypowers(x);
  3. >> plot(x,x,’black’,x,x2,’blue’,x,x3,’green’,x,x4,’red’)

脚本程序

脚本程序与函数程序有诸多不同,如:

前面的图有可以由如下脚本程序实现:

  1. x2 = x .^2;
  2. x3 = x .^3;
  3. x4 = x .^4;
  4. plot (x,x,’black ’,x,x2 ,’blue ’,x,x3 ,’green ’,x,x4 ,’red ’)

将此程序输入到一个新文件里,并保存为mygraphs.m。在命令窗口输入:

  1. >> x = -1:.1:1
  2. >> mygraphs

这里程序需要用到命令窗口里定义的变量x。命令窗口的变量名与脚本文件里的变量名必须一致。

许多人用脚本程序做需要输入多行命令的常规计算,因为比较容易修正错误。

程序注释

当程序行数比较多时,加入注释非常重要,以便能让别人看懂自己的程序,也为了自己备忘。不仅要在程序首部加注释,程序的各个部分也应该加必要的注释。在Matlab里,注释都放在符号%后面。

对于函数程序,至少注释函数的目的、输入输出变量。现在我们把前面写的函数程序加上注释:

  1. function y = myfunc (x)
  2. % Computes the function 2x^2 -3x +1
  3. % Input : x -- a number or vector ;
  4. % for a vector the computation is elementwise
  5. % Output : y -- a number or vector of the same size as x
  6. y = 2*x .^2 - 3*x + 1;

对于脚本程序,程序文件首先注释下文件名会非常方便,如:

  1. % mygraphs
  2. % plots the graphs of x, x^2, x^3, and x^4
  3. % on the interval [ -1 ,1]
  4. % fix the domain and evaluation points
  5. x = -1:.1:1;
  6. % calculate powers
  7. % x1 is just x
  8. x2 = x .^2;
  9. x3 = x .^3;
  10. x4 = x .^4;
  11. % plot each of the graphs
  12. plot (x,x,’+-’,x,x2 ,’x-’,x,x3 ,’o-’,x,x4 ,’--’)

文件存为mygraphs.m,用help命令会输出第一个注释块,如输入命令:

  1. >> help mygraphs

命令窗口会输出

  1. mygraphs
  2. plots the graphs of x, x^2, x^3, and x^4
  3. on the interval [ -1 ,1]
  4. fix the domain and evaluation points

练习

1 写一个带有必要注释的函数程序,计算函数x2ex2,并在区间[-5,5]上画出函数图形。

2 写一个带有必要注释的脚本程序,画出函数sinxsin2xsin3xsin4xsin5xsin6x 在区间[0,2π]上的图形。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注