Saturday 3 November 2012

1.6.2 Function Files

1.6.2 Function Files


Function files are m-files that are used to create new MATLAB functions.
Variables defined and manipulated inside a function file are local to the function,
and they do not operate globally on the workspace. However, arguments
may be passed into and out of a function file.
The general form of a function file isfunction variable(s) = function_name (arguments)
% help text in the usage of the function
%
.
.
end
To illustrate the usage of function files and rules for writing m-file function, let
us study the following two examples.
Example 1.3
Write a function file to solve the equivalent resistance of series connected resistors,
R1, R2, R3, …, Rn.
Solution:
MATLAB Script
function req = equiv_sr(r)
% equiv_sr is a function program for obtaining
% the equivalent resistance of series
% connected resistors
% usage: req = equiv_sr(r)
% r is an input vector of length n
% req is an output, the equivalent resistance(scalar)
%
n = length(r); % number of resistors
req = sum (r); % sum up all resistors
end
The above MATLAB script can be found in the function file equiv_sr.m,
which is available on the disk that accompanies this book.
Suppose we want to find the equivalent resistance of the series connected resistors
10, 20, 15, 16 and 5 ohms. The following statements can be typed in the
MATLAB command window to reference the function equiv_sr
a = [10 20 15 16 5];
Rseries = equiv_sr(a)
diary
The result obtained from MATLAB is
© 1999
Rseries =
66
Example 1.4
Write a MATLAB function to obtain the roots of the quadratic equation
ax2 + bx + c = 0
Solution:
MATLAB Script
function rt = rt_quad(coef)
%
% rt_quad is a function for obtaining the roots of
% of a quadratic equation
% usage: rt = rt_quad(coef)
% coef is the coefficients a,b,c of the quadratic
% equation ax*x + bx + c =0
% rt are the roots, vector of length 2
% coefficient a, b, c are obtained from vector coef
a = coef(1); b = coef(2); c = coef(3);
int = b^2 - 4*a*c;
if int > 0
srint = sqrt(int);
x1= (-b + srint)/(2*a);
x2= (-b - srint)/(2*a);
elseif int == 0
x1= -b/(2*a);
x2= x1;
elseif int < 0
srint = sqrt(-int);
p1 = -b/(2*a);
p2 = srint/(2*a);
x1 = p1+p2*j;
x2 = p1-p2*j;
end
rt =[x1;
x2];
end

No comments:

Post a Comment