• Todd's Matlab讲义第2讲:Matlab 编程


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

    函数程序

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

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

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

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

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

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

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

    • 开头必须是关键词 function
    • 必须有输入输出。
    • 输出变量、函数名和输入变量必须出现在第一行。
    • 输出变量必须要被赋值。

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

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

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

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

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

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

    脚本程序

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

    • 无输入输出
    • 可以改变当前工作区中的变量

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

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

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

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

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

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

    程序注释

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

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

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

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

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

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

    >> help mygraphs
    

    命令窗口会输出

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

    练习

    1 写一个带有必要注释的函数程序,计算函数(x^2e^{-x^2}),并在区间[-5,5]上画出函数图形。

    2 写一个带有必要注释的脚本程序,画出函数(sin x)(sin 2x)(sin 3x)(sin 4x)(sin 5x)(sin 6x) 在区间([0,2pi])上的图形。

  • 相关阅读:
    LeetCode 260
    LeetCode 258
    LeetCode 237
    LeetCode 226
    LeetCode 203
    LeetCode 202
    codeforces 7D
    codefroces 7C
    codeforces 7B
    codeforces 6E (非原创)
  • 原文地址:https://www.cnblogs.com/joyfulphysics/p/4853418.html
Copyright © 2020-2023  润新知