Introduction To MATLAB 7 For Engineers: Functions and Files
Introduction To MATLAB 7 For Engineers: Functions and Files
Introduction To MATLAB 7 For Engineers: Functions and Files
Chapter 3
You can use the lookfor command to find functions that are relevant to your application. For example, type lookfor imaginary to get a list of the functions that deal with imaginary numbers. You will see listed: imag Complex imaginary part i Imaginary unit j Imaginary unit More? See page 142.
Chapter 3
Exponential; e x Square root; x Natural logarithm; ln x Common (base 10) logarithm; log x = log10 x. (continued) Z.R.K
Z.R.K
Z.R.K
abs(x) angle(x) conj(x) imag(x) real(x) Numeric ceil(x) fix(x) floor(x) round(x) sign(x)
3-3
Absolute value. Angle of a complex number. Complex conjugate. Imaginary part of a complex number. Real part of a complex number. Round to nearest integer toward . Round to nearest integer toward zero. Round to nearest integer toward -. Round toward nearest integer. Signum function: +1 if x > 0; 0 Z.R.K if x = 0; -1 if x < 0.
The rectangular and polar representations of the complex number. Rectangular form: M = a + ib.
or
3-4
Z.R.K
(continued )
3-6
Z.R.K
Z.R.K.
2008
Page 1 of 9
Lecture 5
Chapter 3
Operations on Arrays
MATLAB will treat a variable as an array automatically. For example, to compute the Square Roots and the Exponential of 5, 7, and 15, type >>x = [5,7,15]; >>y = sqrt(x) y = 2.2361 2.6358 3.8730 >> y = exp(x) y = 1.0e+006 * 0.0001 0.0011 3.2690
3-7
Z.R.K
(continued )
Every left-facing parenthesis requires a rightfacing mate. However, this condition does not guarantee that the expression is correct! Another common mistake involves expressions like sin2 x , which means (sin x)2. In MATLAB we write this expression as (sin(x))^2, not as: sin^2(x), sin^2x, sin(x^2), or sin(x)^2!
3-9
Z.R.K
Cosine; cos x. Cotangent; cot x. Cosecant; csc x. Secant; sec x. Sine; sin x. Tangent; tan x. Inverse cosine; arccos x. Inverse cotangent; arccot x. Inverse cosecant; arccsc x. Inverse secant; arcsec x. Inverse sine; arcsin x . Inverse tangent; arctan x . Four-quadrant inverse tangent.
Z.R.K
User-Defined Functions
The first line in a function file must begin with a function definition line that has a list of inputs and outputs. This line distinguishes a function M-file from a script M-file. Its syntax is as follows:
Hyperbolic cosine. Hyperbolic cotangent. Hyperbolic cosecant. Hyperbolic secant. Hyperbolic sine. Hyperbolic tangent. Inverse hyperbolic cosine Inverse hyperbolic cotangent Inverse hyperbolic cosecant Inverse hyperbolic secant Inverse hyperbolic sine Inverse hyperbolic tangent;
Z.R.K
Z.R.K.
2008
Page 2 of 9
Lecture 5
User-Defined Functions: Example
Chapter 3
function z = fun(x,y) u = 3*x; z = u + 6*y.^2; Note the use of a semicolon ; at the end of the lines.
This prevents the values of u and z from being displayed. Note also the use of the array exponentiation operator (.^). This enables the function to accept y as an array.
Call this function with its output argument: >>z = fun(3,7) z = 303
The function uses x = 3 and y = 7 to compute z.
3-13
Z.R.K
(continued )
3-14
Z.R.K
(continued )
>>x = 3; y = 7; >>q = fun(x,y); >>x x = 3 >>y y = 7 >>u ??? Undefined function or variable u.
3-15
Z.R.K
(continued )
3-16
(continued )
Z.R.K.
2008
Page 3 of 9
Lecture 5
Function Example
Chapter 3
function [dist,vel] = drop(g,vO,t); % Computes the distance travelled and the % velocity of a dropped object, % as functions of g, % the initial velocity vO, and % the time t. vel = g*t + vO; dist = 0.5*g*t.^2 + vO*t; 1. The variable names used in the function definition may, but need not, be used when the function is called: >>a = 9.81; % in SI (32.2 in BS) >>initial_speed = 10; >>time = 5; >>[feet_dropped,speed] = . . . drop(a,initial_speed,time)
3-19
Z.R.K
Function Example (continued) 2. The input variables need not be assigned values outside the function prior to the function call: >>[feet_dropped,speed] = drop(9.81,10,5) 3. The inputs and outputs may be arrays: >>[feet_dropped,speed]=drop(9.81,10,[0:1:5]) This function call produces the arrays feet_dropped and speed, each with six values corresponding to the six More? See pages 148-153. values of time in the array time.
Local Variables
The names of the input variables given in the function definition line are local to that function. This means that other variable names can be used when you call the function. All variables inside a function are erased after the function finishes executing, except when the same variable names appear in the output variable list used in the function call.
3-20
Z.R.K
(continued )
global Variables
The global command declares certain variables global, and therefore their values are available to the basic workspace and to other functions that declare these variables global. The syntax to declare the variables a, x, and q is
>>fzero(function, x0)
where function is a string containing the name of the function, and x0 is a user-supplied guess for the zero. The fzero function returns a value of x that is near x0. It identifies only points where the function crosses the x-axis, not points where the function just touches the axis. For example, fzero(cos,2) returns the value 1.5708.
3-22
Z.R.K
>>global a x q
Any assignment to those variables, in any function or in the base workspace, is available to all the other functions declaring them global.
3-21
Z.R.K
= x + 2e-x - 3.
Figure 3.21
Using fzero with User-Defined Functions To use the fzero function to find the zeros of
more complicated functions, it is more convenient to define the function in a function file. For example, if y = x + 2e-x -3, define the following function file:
zero near
x = -0.5
and one near
x = 3.
>>x = fzero(f1,-0.5)
The answer is x = -0.5881.
>>x = fzero(f1, 3)
The answer is x = 2.xxxx.
3-23
Z.R.K
(continued )
3-24
Z.R.K
Z.R.K.
2008
Page 4 of 9
Lecture 5
Chapter 3
fminbnd
The fminbnd function finds the minimum of a function of a single variable, which is denoted by x. fminbnd will find a minimum that occurs on a boundary x1-x2. One form of its syntax is
When using fminbnd it is more convenient to define the function in a function file. For example, if y = 1 - xe -x , define the following function file: function y = f2(x) y = 1-x.*exp(-x); To find the value of x that gives a minimum of y for 0 x 5, type >>x = fminbnd(f2,0,5) The answer is x = 1. To find the minimum value of y, type y = f2(x). The result is y = 0.6321. A function can have one or more local minima and a global minimum. If the specified range of the independent variable does not enclose the global minimum, fminbnd will not find the global minimum. fminbnd will find a minimum that occurs on a boundary. Z.R.K
3-26
- To find the minimum of a function of more than one variable, use the fminsearch function. One form of its syntax is
fminsearch(function, x0)
where function is a string containing the name of the function. The vector x0 is a guess that must be supplied by the user. 2 2 - To minimize the function f = xe-x - y , we first define it in an M-file, using the vector x whose elements are (x(1) = x and x(2) = y). function f = f4(x) f = x(1).*exp(-x(1).^2-x(2).^2); Suppose we guess that the minimum is near x = y = 0. The session is >>fminsearch(f4,[0,0]) ans = -0.7071 0.000 Thus the minimum occurs at x = 0.7071, y = 0. Z.R.K 3-28
3-27
Z.R.K
Function Handles @
You can create a function handle to any function by using the at sign, @, before the function name. You can then name the handle if you wish, and use the handle to reference the function. For example, to create a handle to the sine function, you type
Function Handles @
(continued)
This is a rather cumbersome way to plot the sine function, but the concept can be extended to create a general purpose plotting function that accepts a function as an input. For example,
>>sine_handle = @sin;
where sine_handle is a user-selected name for the handle. A common use of a function handle is to pass the function as an argument to another function. For example, we can plot sin x over 0 x 6 as follows:
>>gen_plot(sine_handle,[0:0.01:6]) or >>gen_plot(@sin,[0:0.01:6])
For example, this function gen_plot may be used as follows with a function handle array, to create two subplots, one for the sine and one for the cosine.
>>plot([0:0.01:6],sine_handle,[0:0.01:6])?!
3-29
Z.R.K
(continued )
3-30
fh(1) = @sin; fh(2) = @cos; for k = 1:2 subplot(2,1,k) gen_plot(fh(k),[0:0.01:8]) Z.R.K end
Z.R.K.
2008
Page 5 of 9
Lecture 5
Chapter 3
(continued )
(continued )
(continued )
3-34
Z.R.K
(continued )
Z.R.K.
2008
Page 6 of 9
Lecture 5
Chapter 3
The syntax for creating an anonymous function from an expression is fhandle = @(arglist) expr where arglist is a comma-separated list of input arguments to be passed to the function, and expr is any single, valid MATLAB expression. To create a simple function called sq to calculate the square of a number, type >>sq = @(x) x.^2; To improve readability, you may enclose the expression in parentheses, as sq = @(x) (x.^2);. To execute the function, type the name of the function handle, followed by any input arguments enclosed in parentheses. For example, >>sq([5,7]) ans = 25 49
3-38
Z.R.K
(continued )
(continued )
(continued )
Subfunctions
A function M-file may contain more than one user-defined function. The first defined function in the file is called the primary function, whose name is the same as the M-file name. All other functions in the file are called subfunctions. Subfunctions are normally visible only to the primary function and other subfunctions in the same file; that is, they normally cannot be called by programs or functions outside the file. However, this limitation can be removed with the use of function handles. Create the primary function first with a function definition line and its defining code, and name the file with this function name as usual. Then create each subfunction with its own function definition line and defining code. The order of the subfunctions does not matter, but function names must be unique within the M-file.
3-42
Z.R.K
>>f = @(x) x.^3; >>g = @(x) 5*sin(x); >>h = @(x) g(f(x)); >>h(2) ans = 4.9468
3-41
Z.R.K
Z.R.K.
2008
Page 7 of 9
Lecture 5
Chapter 3
(continued )
(continued )
Example (continued)
A sample session follows.
Nested Functions
With MATLAB 7 you can now place the definitions of one or more functions within another function. Functions so defined are said to be nested within the main function. You can also nest functions within other nested functions. Like any M-file function, a nested function contains the usual components of an M-file function. You must, however, always terminate a nested function with an end statement. In fact, if an M-file contains at least one nested function, you must terminate all functions, including subfunctions, in the file with an end statement, whether or not they contain nested functions. The following example constructs a function handle for a nested function and then passes the handle to the
3-46
Z.R.K
(continued )
MATLAB function fminbnd to find the minimum point on a parabola. The parabola function constructs and returns a function handle f for the nested function p. This handle gets passed to fminbnd. function f = parabola(a, b, c) f = @p; function y = p(x) y = a*x^2 + b*x + c; end end In the Command window type >>f = parabola(4, -50, 5); >>fminbnd(f, -10, 10) ans = 6.2500 Note than the function p(x) can see the variables a, b, and c in the calling functions workspace.
3-47
Z.R.K
Nested functions might seem to be the same as subfunctions, but they are not. Nested functions have two unique properties: 1. A nested function can access the workspaces of all functions inside of which it is nested. So for example, a variable that has a value assigned to it by the primary function can be read or overwritten by a function nested at any level within the main function. A variable assigned in a nested function can be read or overwritten by any of the functions containing that function. 2. If you construct a function handle for a nested function, the handle not only stores the information needed to access the nested function; it also stores the values of all variables shared between the nested function and those functions that contain it. This means that these variables persist in memory between calls made by means of the function handle.
3-48
Z.R.K
(continued )
Z.R.K.
2008
Page 8 of 9
Lecture 5
Private Functions
Chapter 3
Private functions reside in subdirectories with the special name private, and they are visible only to functions in the parent directory. Assume the directory circuits is on the MATLAB search path. A subdirectory of circuits called private may contain functions that only the functions in circuits can call. Because private functions are invisible outside the parent directory circuits, they can use the same names as functions in other directories. Primary functions and subfunctions can be implemented as private functions. Create a private directory by creating a subdirectory called private using the standard procedure for creating a directory or a folder on your computer, but do not place the private directory on your path.
3-49
Z.R.K
(continued )
3-52
Z.R.K
Figure 3.41
End of Chapter 3
www.ju.edu.jo\zkhatib
3-53
Z.R.K
Z.R.J.K Z.R.K
Z.R.K.
2008
Page 9 of 9