我们在第二章提过的 M-file 除了可以撰写程式外,还有另一个重要的用途,就是可以用来定义函数。这样的函数称为M-档定义的函数, 然后储存起来,就可以和那些内建的函数(如sin, cos,log等)一样的自由使用。举例来说,我们可以定义一函 数cirarea是计算圆的面积,以下的 M-file: cirarea.m就是定义这个函数
% M-file function, cirarea.m
% Calculate the area of a circle with raduis r
% r can be a scalar or an array
function c=cirarea(r)
c=pi*r.^2;
令一个例子是MATLAB内建的函数linspace
function y = linspace(d1, d2, n)
% LINSPACE Linearly spaced vector.
% LINSPACE(x1, x2) generates a row vector of 100 linearly
% equally spaced points between x1 and x2.
% LINSPACE(x1, x2, N) generates N points between x1 and x2.
%
% See also LOGSPACE, :.
% Copyright (c) 1984-94 by The MathWorks, Inc.
if nargin == 2
n = 100;
end
y = [d1+(0:n-2)*(d2-d1)/(n-1) d2];
M-file定义的函数有其语法的一些规定:
>> r=1:3;
>> ar=cirarea(r) % 呼叫 cirarea.m 函数,以阵列 r 为输入变数
ar =
3.1416 12.5664 28.2743
>> disp(ar) % 指令 disp 可以将变数值直接列出
3.1416 12.5664 28.2743
![]()