今天来给各位说下如何在Matlab
中调用函数,MATLAB®内置了大量执行计算任务的函数,尤其随着版本的迭代,内置的函数会越来越多。在其他编程语言中,函数等同于子例程或方法。本文,将以几个例子来说明Matlab
中调用函数的具体方法,由于不同函数调用方式不同,这里只能作为参考。
要调用函数,例如max
,请将其输入参数括在圆括号中:
>> A = [1 3 5];
>> max(A)
ans =
5
如果存在多个输入参数,请使用逗号加以分隔:
>> B = [3 6 9];
>> union(A,B)
ans =
1 3 5 6 9
通过将函数赋值给变量,返回该函数的输出:
>> maxA = max(A)
maxA =
5
如果存在多个输出参数,请将其括在方括号中:这里需要注意,bounds
边界函数在Matlab R2021b
中引入,之前的版本会报错不存在该函数
[minA,maxA] = bounds(A)
minA = 1
maxA = 5
用引号将任何文本输入括起来:
disp("hello world")
hello world
有关双引号的用法,需要Matlab
版本高于R2017a
。
要调用不需要任何输入且不会返回任何输出的函数,请只键入函数名称:
clc
clc
函数清空命令行窗口。
需要注意的是,当你不了解你想要调用函数的输入参数和输出结果时,可以通过help
获取该函数的使用帮助文档。例如:
>> help max
max Largest component.
For vectors, max(X) is the largest element in X. For matrices,
max(X) is a row vector containing the maximum element from each
column. For N-D arrays, max(X) operates along the first
non-singleton dimension.
[Y,I] = max(X) returns the indices of the maximum values in vector I.
If the values along the first non-singleton dimension contain more
than one maximal element, the index of the first one is returned.
max(X,Y) returns an array the same size as X and Y with the
largest elements taken from X or Y. Either one can be a scalar.
[Y,I] = max(X,[],DIM) operates along the dimension DIM.
When X is complex, the maximum is computed using the magnitude
max(ABS(X)). In the case of equal magnitude elements, then the phase
angle max(ANGLE(X)) is used.
max(..., NANFLAG) specifies how NaN (Not-A-Number) values are treated.
NANFLAG can be:
'omitnan' - Ignores all NaN values and returns the maximum of the
non-NaN elements. If all elements are NaN, then the
first one is returned.
'includenan' - Returns NaN if there is any NaN value. The index points
to the first NaN element.
Default is 'omitnan'.
Example: If X = [2 8 4; 7 3 9] then
max(X,[],1) is [7 8 9],
max(X,[],2) is [8; 9] and
max(X,5) is [5 8 5; 7 5 9].
转载文章,原文出处:MathWorks官网,由古哥整理发布
如若转载,请注明出处:https://iymark.com/articles/2852.html