matlab快速入门(25):匿名函数+主函数子函数

MATLAB匿名函数

一个匿名的函数就像是在传统的编程语言,在一个单一的 MATLAB 语句定义一个内联函数。

它由一个单一的 MATLAB 表达式和任意数量的输入和输出参数。

在MATLAB命令行或在一个函数或脚本可以定义一个匿名函数。

这种方式,可以创建简单的函数,而不必为他们创建一个文件。

建立一个匿名函数表达式的语法如下:

f = @(arglist)expression

在这个例子中,我们将编写一个匿名函数 power,这将需要两个数字作为输入并返回第二个数字到第一个数字次幂。

在MATLAB中建立一个脚本文件,并输入下述代码:

power = @(x, n) x.^n;
result1 = power(7, 3)
result2 = power(49, 0.5)
result3 = power(10, -10)
result4 = power (4.5, 1.5)

运行如下:

matlab主函数和子函数

举个例子就明白了,如下:

我们写一个 quadratic 函数来计算一元二次方程的根。

该函数将需要三个输入端,二次系数,线性合作高效的和常数项,它会返回根。 

函数文件 quadratic.m 将包含的主要 quadratic 函数和子函数 disc 来计算判别。

在MATLAB中建立一个函数文件 quadratic.m 并输入下述代码:

function [x1,x2] = quadratic(a,b,c)
%this function returns the roots of 
% a quadratic equation.
% It takes 3 input arguments
% which are the co-efficients of x2, x and the 
%constant term
% It returns the roots
d = disc(a,b,c); 
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of quadratic

function dis = disc(a,b,c) 
%function calculates the discriminant
dis = sqrt(b^2 - 4*a*c);
end % end of sub-function

验证:

 

posted @ 2021-07-31 01:59  川川菜鸟  阅读(1063)  评论(0编辑  收藏  举报