MATLAB函数

2022-01-13 11:57 更新

`function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN)`

详细例子

```function max = mymax(n1, n2, n3, n4, n5)
%This function calculates the maximum of the
% five numbers given as input
max =  n1;
if(n2 > max)
max = n2;
end
if(n3 > max)
max = n3;
end
if(n4 > max)
max = n4;
end
if(n5 > max)
max = n5;
end```

`help mymax`

MATLAB执行上述语句，返回以下结果：

```This function calculates the maximum of the
five numbers given as input
```

`mymax(34, 78, 89, 23, 11)`

MATLAB执行上述语句，返回以下结果：

```ans =
89
```

MATLAB匿名函数

`f = @(arglist)expression`

详细例子

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

```result1 =
343
result2 =
7
result3 =
1.0000e-10
result4 =
9.5459
```

详细例子

```function [x1,x2] = quadratic(a,b,c)
%this function returns the roots of
% 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);

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

`quadratic(2,4,-4)`

MATLAB执行上面的语句，返回以下结果：

```ans =
0.7321
```

MATLAB嵌套函数

```function x = A(p1, p2)
...
B(p2)
function y = B(p3)
...
end
...
end```

详细例子

```function [x1,x2] = quadratic2(a,b,c)
function disc  % nested function
d = sqrt(b^2 - 4*a*c);
end % end of function disc
disc;
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of function quadratic2```

`quadratic2(2,4,-4)`

MATLAB执行上面的语句，返回以下结果：

```ans =
0.7321
```

详细例子

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

```function [x1,x2] = quadratic3(a,b,c)
%this function returns the roots of
% 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);

`quadratic3(2,4,-4)`

MATLAB执行上面的语句，返回以下结果：

```ans =
0.7321
```

详细例子

```function avg = average(nums)
global TOTAL
avg = sum(nums)/TOTAL;
end```

```global TOTAL;
TOTAL = 10;
n = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42];
av = average(n)```

```av =
35.5000```

App下载