# Matlab函數

``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``````

``````Trial>> help mymax
This function calculates the maximum of the
five numbers given as input``````

``mymax(11,22,35,81,198)``

``````Trial>> mymax(11,22,35,81,198)

ans =

198``````

## 匿名函數

``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``````

``````Trial>> quadratic(2,4,-4)

ans =

0.7321``````

## 嵌套函數

``````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``````

``````Trial>> quadratic2(2,4,-4)

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-efficient 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);

``````Trial>> quadratic3(2,4,-4)

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)``````

``````Trial>> global TOTAL;
TOTAL = 10;
n = [36, 45, 35, 45, 33, 29, 50, 41, 58, 47];
av = average(n)

av =

41.9000``````