1. Chapter 5: FUNCTIONS IN MATLAB
5.1 Why Use Functions
1. Avoid duplicate code.
2. Limit the effect of changes to specific sections of a program.
3. Promote program reuse.
4. Reduce the complexity of the overall program by making it more
readable and manageable.
5. Isolate complex operations.
6. Improve portability.
7. Make debugging and error isolation easier.
8. Improve performance because each function can be “optimized.”
2. Chapter 5: FUNCTIONS IN MATLAB
5.2 USER-DEFINED FUNCTIONS
% Comments
function [OutputVariables] = FunctionName(InputVariables)
% Comments
Expressions
OutputVariables = . . .
The comments immediately following the function interface statement are
used by MATLAB to create this function’s Help information—that is, when
one types at the command line
>> help FunctionName
Special Case 1
Functions can also be used to create a figure, to display annotated data to the
command window, or to write data to files.
function FunctionName(InputVariables)
3. Chapter 5: FUNCTIONS IN MATLAB
5.2 USER-DEFINED FUNCTIONS
Special Case 2
When a function is used only to store data in a prescribed manner, the
function does not require any input arguments. In this case, the function
interface line has the form
function OutputVariables = FunctionName
Special Case 3
When a function is a primary function and the primary function is being used
instead of script file, the function interface line has the form
function FunctionName
4. Chapter 5: FUNCTIONS IN MATLAB
function [x, y] = ComputeXY(t, a, b, c)
% Computation of -
% x = cos(at)+b
% y = ƒxƒ+c
% Scalars: a, b, c
% Vectors: t, x, y
x = cos(a*t)+b;
y = abs(x)+c;
[u, v] = ComputeXY(0:pi/4:pi, 1.4, 2, 0.75);
Functions normally return to the calling program when the last statement of
the function is reached. To force an earlier return, one uses
return
5. Chapter 5: FUNCTIONS IN MATLAB
function [x, y] = ComputeXY(t, a, b, c)
if (length(x) == 1)||(nargin ~= 4)
x = NaN;
y = NaN;
return
end
x = cos(a*t)+b;
y = abs(x)+c;
To share the global memory of the script or function or to create access to global
variables for use by various functions.2 This access is provided by
global
function [x, y] = ComputeXY(t)
global A B C
x = cos(A*t)+B;
y = abs(x)+C;
The script required to call this function is now
global A B C
A = 1.4; B = 2; C = 0.75;
[u, v] = ComputeXY(0:pi/4:pi)
6. Chapter 5: FUNCTIONS IN MATLAB
function [x, y] = ComputeXY(t, a, b, c)
x = cos(a*t)+b;
y = abs(x)+c;
---------------------------------------------------
n = 3;
a = linspace(1, 1.4, n);
for k = 1:n
[u, v] = ComputeXY(0:pi/4:pi, a(k),
sqrt(1.8/(1+k)^3), 1/.85);
disp(['For k = ', int2str(k)])
disp(['u = ' num2str(u)])
disp(['v = ' num2str(v)])
end
7. Chapter 5: FUNCTIONS IN MATLAB
Subfunctions
function [m, s] = MeanStdDev(dat) % Primary function
n = length(dat);
m = meen(dat, n);
s = stdev(dat, n);
function m = meen(v, n) % Subfunction
m = sum(v)/n;
function sd = stdev(v, n) % Subfunction
m = meen(v, n); % Calls a sub function
sd = sqrt((sum(v.^2)-n*m^2)/(n-1));
8. Chapter 5: FUNCTIONS IN MATLAB
Anonymous Functions
Another way to create a function, either in the command window, a script, a
primary function, or subfunction is by creating an anonymous function. It
can be composed of only one expression, and it can bring
back only one variable. Any function requiring logic or multiple operations to
arrive at the result cannot employ the anonymous function.
functionhandle = @(arguments) (expression)
bet = pi/3;
cx = @(x) (abs(cos(bet*x)));
disp(cx(4.1))
cx = @(x, bet) (abs(cos(bet*x)));
cxrt = @(x, bet) (cx(x, bet)^(1/3));
disp(cxrt(4.1, pi/3))
v = @(x, y) ([0.25*x.^2+y.^2-1; y-4*x.^2+3]);
a = v(1, 2);
disp(['v(1,1) = 'num2str(a(1))' v(2,1) = ' num2str(a(2))])
9. Chapter 5: FUNCTIONS IN MATLAB
Inline Another way to create a local function, either in the command window, a
script, a primary function, or subfunction is by using inline.
=> Cannot call another inline function, but it can use a
user-created function existing as a function file.
FunctionName = inline ('expression', 'v1','v2', . . . )
FofX = inline('x.^2.*cos(a*x)-b', 'x', 'a', 'b');
g = FofX([pi/3, pi/3.5], 4, 1)
10. Chapter 5: FUNCTIONS IN MATLAB
5.4 MATLAB FUNCTIONS THAT OPERATE ON ARRAYS OF DATA
Fitting Data with Polynomials—polyfit/polyval
c = polyfit(x, y, n)
y = polyval(c, xnew)
y = polyval(polyfit(x, y), xnew)
function Example5_1
ncs = NeuberData;
c = polyfit(ncs(:, 1), ncs(:, 2), 4);
r = input('Enter notch radius (0 < r < 5 mm): ');
Su = input('Enter ultimate strength of steel (0.3 < Su < 1.7 GPa): ');
q = 1/(1+polyval(c, Su)/sqrt(r));
disp('Notch sensitivity = ' num2str(q, 3)])
function nd = NeuberData
nd = [0.34, 0.66; 0.48, 0.46; 0.62, 0.36; 0.76, 0.29; 0.90, 0.23; 1.03, 0.19; ...
1.17, 0.14; 1.31, 0.10; 1.45, 0.075; 1.59, 0.050; 1.72, 0.036];
11. Chapter 5: FUNCTIONS IN MATLAB
5.4 MATLAB FUNCTIONS THAT OPERATE ON ARRAYS OF DATA
Fitting Data with spline Y = spline(x, y, X)
function f = DampedSineWave(tau, xi)
r = sqrt(1-xi^2);
phi = atan(r/xi);
f = exp(-xi*tau).*sin(tau*r+phi)/r;
n = 12; xi = 0.1;
tau = linspace(0, 20, n);
data = DampedSineWave(tau, xi);
newtau = linspace(0, 20, 200);
yspline = spline(tau, data, newtau);
yexact = DampedSineWave(newtau, xi);
plot(newtau, yspline, 'k—', newtau, yexact, 'k-')
12. Chapter 5: FUNCTIONS IN MATLAB
5.4 MATLAB FUNCTIONS THAT OPERATE ON ARRAYS OF DATA
Interpolation of Data—interp1
V = interp1(u, v, U)
13. Chapter 5: FUNCTIONS IN MATLAB
5.4 MATLAB FUNCTIONS THAT OPERATE ON ARRAYS OF DATA
Numerical Integration—trapz
Area = trapz(x, y)
xi = 0.1;
tau = linspace(0, 20, 200);
ftau = DampedSineWave(tau, xi);
Area = trapz(tau, ftau)
Area of a Polygon—polyarea polyarea(x, y)
a = 2; b = 5;
t = linspace(0, 2*pi, 11);
x = a*cos(t);
y = b*sin(t);
disp(['Area = ' num2str(polyarea(x, y))])
14. Chapter 5: FUNCTIONS IN MATLAB
5.4 MATLAB FUNCTIONS THAT OPERATE ON ARRAYS OF DATA
Digital Signal Processing—fft and ifft
k = 5; m = 10; fo = 10; Bo = 2.5;
N = 2^m; T = 2^k/fo;
ts = (0:N-1)*T/N;
df = (0:N/2-1)/T;
whamm = 0.54-0.46*cos(2*pi*ts/T);
SampledSignal = Bo*sin(2*pi*fo*ts);
k1 = sum(whamm.*SampledSignal)/sum(whamm);
k2 = sqrt(N/sum(whamm.^2));
CorrectedSignal = whamm.*(SampledSignal-k1)*k2;
figure(1)
plot(ts, CorrectedSignal)
figure(2)
An = abs(fft(CorrectedSignal, N))/N;
plot(df, 2*An(1:N/2))
disp(['Average power = ' num2str(sum(An.^2))])
15. Chapter 5: FUNCTIONS IN MATLAB
5.5 MATLAB FUNCTIONS THAT REQUIRE USER-DEFINED
FUNCTIONS
fzero Finds one root of f(x) = 0
roots Finds the roots of a polynomial
quadl Numerically integrates f(x) in a specified interval
dblquad Numerically integrates ( , ) in a specified region
ode45 Solves a system of ordinary differential equations with prescribed
initial conditions
bvp4c Solves a system of ordinary differential equations with prescribed
boundary conditions
dde23 Solves delay differential equations with constant delays and with
prescribed initial conditions
fminbnd Finds a local minimum of ( ) in a specified interval
fsolve Numerically solves a system of nonlinear equations
16. Chapter 5: FUNCTIONS IN MATLAB
5.5 MATLAB FUNCTIONS THAT REQUIRE USER-DEFINED
FUNCTIONS
Zeros of Functions—fzero and roots/poly
x = fzero(@FunctionName, x0, options, p1, p2, . . . )
function z = FunctionName(x,p1,p2, . . . )
Expressions
z = . . .
fhandle = @(x, p1, p2, . . . ) (Expression);
z = fzero(fhandle, x0, options, p1, p2, . . . )
InlineFunctionName = inline('Expression', 'x', 'p1', 'p2', . . . );
z = fzero(InlineFunctionName, x0, options, p1, p2, . . . )
17. Chapter 5: FUNCTIONS IN MATLAB
5.5 MATLAB FUNCTIONS THAT REQUIRE USER-DEFINED
FUNCTIONS
Zeros of Functions—fzero and roots/poly
w = fzero(@cos, 2*pi)/pi
w = fzero(@cos, 2.04*pi)/pi
w = fzero(@cos, [0, 2*pi])/pi
function Rt = FindZeros(FunName, Nroot, x,
w)
f = feval(FunName, x, w);
indx = find(f(1:end-1).*f(2:end)<0);
L = length(indx);
if L<Nroot
Nroot = L;
end
Rt = zeros(Nroot, 1);
for k = 1:Nroot
Rt(k) = fzero(FunName, [x(indx(k)), x(indx(k)
+1)], [], w);
end
18. Chapter 5: FUNCTIONS IN MATLAB
5.6 SYMBOLIC SOLUTIONS AND CONVERTING SYMBOLIC
EXPRESSIONS INTO FUNCTIONS
fnct = inline(vectorize(f), 'x', 'y', 'z')
fnct = matlabFunction(f, 'vars', [x, y, z])
fnct = @(x, y, z) (f)
syms s t
syms xi real
den = s*(s^2+2*xi*s+1);
yt = ilaplace(1/den, s, t);
yoft = inline(vectorize(yt), 't', 'xi');
t = linspace(0, 20, 200); xi = 0.15;
plot(t, real(yoft(t, xi)))
syms s t
syms xi real
den = s*(s^2+2*xi*s+1);
yt = ilaplace(1/den, s, t);
yoft = matlabFunction(yt, 'vars', [t, xi]);
t = linspace(0, 20, 200); xi = 0.15;
plot(t, real(yoft(t, xi)))
19. Chapter 5: FUNCTIONS IN MATLAB
5.6 SYMBOLIC SOLUTIONS AND CONVERTING SYMBOLIC
EXPRESSIONS INTO FUNCTIONS
syms t xi n r a
r = sqrt(1- xi^2);
arg = exp(xi*n)*sin(r*(t-n));
yt = exp(-xi*t)*int(arg, n, 0, t)/r;
yoft = inline(vectorize(yt), 't', 'xi');
tt = linspace(0, 20, 200); z = 0.15;
plot(tt, yoft(tt, z))
20. Chapter 5: FUNCTIONS IN MATLAB
5.6 SYMBOLIC SOLUTIONS AND CONVERTING SYMBOLIC
EXPRESSIONS INTO FUNCTIONS
z = 0.15;
syms t xi n r a
r = sqrt(1- xi^2);
arg = exp(xi*n)*sin(r*(t-n));
yt = exp(-xi*t)*int(arg, n, 0, t)/r;
yoft = inline(vectorize(yt), 't', 'xi');
dydt = inline(vectorize(diff(yt, t)), 't', 'xi');
tmax = fzero(dydt, [3 5],[], z);
ymax = yoft(tmax, z);
disp('ymax = ' num2str(ymax) ' tmax = '
num2str(tmax)])
d2ydt2 = inline(vectorize(diff(yt, t, 2)), 't', 'xi');
secder = d2ydt2(tmax, z);
disp(['Second derivative at tmax = '
num2str(secder)])
z = 0.15;
syms t xi n r a
r = sqrt(1- xi^2);
arg = exp(xi*n)*sin(r*(t-n));
yt = exp(-xi*t)*int(arg, n, 0, t)/r;
ytrise = inline(vectorize(yt-a), 't', 'xi',
'a');
t9 = fzero(ytrise, [0 2], [], z, 0.9);
t1 = fzero(ytrise, [0 2], [], z, 0.1);
disp(['Rise time = ' num2str(t9-t1)])
21. Chapter 5: FUNCTIONS IN MATLAB
5.6 SYMBOLIC SOLUTIONS AND CONVERTING SYMBOLIC
EXPRESSIONS INTO FUNCTIONS
Symbolic solution of algebraic equations
z = solve('Eqn1', 'Eqn2', . . . , 'EqnN', 'Var1', 'Var2', ..., 'VarN')
z = solve('x^2/4+y^2-1', 'y-4*x^2+3', 'x', 'y')
x = z.x
y = z.y
z = solve('x^2/4+y^2-1', 'y-4*x^2+3', 'x', 'y');
v = [double(z.x) double(z.y)];
disp([' x y'])
disp(v)
Symbolic solution of a differential equation
z = dsolve('Eqn1', 'Eqn2', . . . , 'EqnN', 'BC1', 'BC2', . . . , 'BCM', 'v')
syms x
r = dsolve('D4w-sin(pi*x)','w(0) = 0', 'Dw(0) = 0', 'D3w(1) = 0', 'D2w(1) = 0', 'x');
dis = inline(vectorize(r), 'x');
disp(['Displacement at the free end = ' num2str(dis(1))])