function的用法()

xiaoxiao2022-06-11  34

摘自matlab

function Add new function. New functions may be added to MATLAB’s vocabulary if they are expressed in terms of other existing functions. The commands and functions that comprise the new function must be put in a file whose name defines the name of the new function, with a filename extension of ‘.m’. At the top of the file must be a line that contains the syntax definition for the new function. For example, the existence of a file on disk called STAT.M with:

function [mean,stdev] = stat(x) %STAT Interesting statistics. n = length(x); mean = sum(x) / n; stdev = sqrt(sum((x - mean).^2)/n); defines a new function called STAT that calculates the mean and standard deviation of a vector. The variables within the body of the function are all local variables. See SCRIPT for procedures that work globally on the work- space. A subfunction that is visible to the other functions in the same file is created by defining a new function with the function keyword after the body of the preceding function or subfunction. For example, avg is a subfunction within the file STAT.M: function [mean,stdev] = stat(x) %STAT Interesting statistics. n = length(x); mean = avg(x,n); stdev = sqrt(sum((x-avg(x,n)).^2)/n); %------------------------- function mean = avg(x,n) %AVG subfunction mean = sum(x)/n; Subfunctions are not visible outside the file where they are defined. You can terminate any function with an END statement but, in most cases, this is optional. END statements are required only in MATLAB files that employ one or more nested functions. Within such a file, every function (including primary, nested, private, and subfunctions) must be terminated with an END statement. You can terminate any function type with END, but doing so is not required unless the file contains a nested function. Normally functions return when the end of the function is reached. A RETURN statement can be used to force an early return.

用法(翻译)

function用来创建一个新的函数。 如果一个新的函数在现有的matlab库中不存在,那么它将会自动添加进matlab库中。组成新函数的命令和函数必须放在一个文件中,该文件的名称定义了新函数的名称,生成一个.m的文件。文件的顶部必须有一行包含新函数的语法定义,例如,磁盘上存在一个名为STAT.M的文件,其中: function [mean,stdev] = stat(x) %STAT Interesting statistics. n = length(x); mean = sum(x) / n; stdev = sqrt(sum((x - mean).^2)/n);

定义了一个STAT函数计算向量的均值和标准差。函数体内的变量都是局部变量。有关在工作空间上全局工作的过程,请参阅脚本。

通过在前一个函数或子函数的主体后面用function关键字定义一个新函数,可以创建对同一文件中的其他函数可见的子函数。例如,avg是文件status . m中的子函数: function [mean,stdev] = stat(x) %STAT Interesting statistics. n = length(x); mean = avg(x,n); stdev = sqrt(sum((x-avg(x,n)).^2)/n);

%------------------------- function mean = avg(x,n) %AVG subfunction mean = sum(x)/n;

子函数在定义它们的文件之外是不可见的。 = = 子函数的写法和调用可以百度。百度有详解

转载请注明原文地址: https://www.6miu.com/read-4930516.html

最新回复(0)