1 / 29

Essential MATLAB® for Engineers and Scientists

Essential MATLAB® for Engineers and Scientists. Brian D. Hahn and Daniel T. Valentine Third edition. Function M-files. The objective of this chapter is to enable you to: Represent your own functions with inline objects and function M-files .

ashley
Download Presentation

Essential MATLAB® for Engineers and Scientists

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Essential MATLAB®forEngineers and Scientists Brian D. Hahn and Daniel T. Valentine Third edition

  2. Function M-files • The objective of this chapter is to enable you to: • Represent your own functions with inline objects and function M-files. • We have already seen that MATLAB has a number of built-in (compiled) functions, e.g. sin , sqrt , sum . You can verify that they are built-in by attempting to type them. Try type sin for example. • MATLAB enables you to create your own function M-files.

  3. Cont. A function M-file is similar to a script file in that it also has a .m extension. a function M-file differs from a script file in that a function M-fil communicates with the MATLAB workspace only through specially designated input and output arguments . Functions are indispensable when it comes to breaking a problem down into manageable logical pieces.

  4. 10.1 Some examples10.1.1 Inline objects: harmonic oscillators • If two coupled harmonic oscillators, e.g. two masses connected with a spring on a very smooth table, are considered as a single system, the output of the system as a function of time t could be given by something like: • h(t) = cos(8t) + cos(9t) • You can represent h (t ) at the command line by creating an inline object as follows: • h = inline( ’cos(8*t) + cos(9*t)’ );

  5. Cont. • Now write some MATLAB statements in the Command Window which use your function h to draw the graph: • x = 0 : pi/40 : 6*pi; • plot(x, h(x)), grid • The variable t in the inline definition of h is the input argument . It is essentially a ‘dummy’ variable, and serves only to provide input to the function from the outside world. You can use any variable name here; it doesn’t have to be the same as the one used when you invoke (use) the function.

  6. Cont. • You can create functions of more than one argument with inline . For example, • f = inline( ’x.ˆ2 + y.ˆ2’, ’x’, ’y’ ); • f(1, 2) • ans = 5

  7. 10.1.2 Function M-files: Newton’s method again • Newton’s method may be used to solve a general equation f(x) = 0 by repeating the assignment xbecomes x – • where f’(x ) (i.e. df/dx ) is the first derivative of f (x) • Suppose that f (x)=x3 +x − 3, i.e. we want to solve the equation x3 +x − 3= 0.We have to be able to differentiate f(x).That’s quite easy here:f’(x)= 3x2 + 1.We could write inline objects for both f (x) and f’(x), but for this example we will use function M-files instead.

  8. Cont. • Use the Editor to create and save (in the current MATLAB directory) the function file f.m as follows: • function y = f(x) • y = xˆ3 + x - 3; • Then create and save another function file df.m: • function y = df(x) • y = 3*xˆ2 + 1; • Now write a separate script file, newtgen.m (in the same directory), which will stop either when the relative error in x is less than 10−8 , or after 20 steps,

  9. Cont. • % Newton’s method in general • % exclude zero roots! • steps = 0; % iteration counter • x = input( ’Initial guess: ’ ); % estimate of root • re = 1e-8; % required relative error • myrel= 1; • while myrel > re & (steps < 20) • xold= x; • x = x - f(x)/df(x); • steps = steps + 1;

  10. Cont. • disp( [x f(x)] ) • myrel= abs((x-xold)/x); • end; • if myrel <= re • disp( ’Zerofoundat’ ) • disp( x ) • else • disp( ’Zero NOT found’ ) • end; • Note that there are two conditions that will stop the while loop: convergence, or the completion of 20 steps.

  11. Cont. • The variable y in the function files f.m and df.m is the output argument . It is a dummy variable, and defines how output will be sent back to the outside world. • By the way, you realize of course that you can use your own functions from the command line, don’t you? For example, • f(2) • should return 7 with f.m defined as above.

  12. 10.2 Basic rules • Try the following more general example, which returns the mean (avg ) and standard deviation (stdev)of the values in the vector x . • Although there are two MATLAB functions to do this (mean and std), it is useful to have them combined into one. Write a function filestats.m: • function [avg, stdev] = stats( x ) • avg= mean(x); % function body • stdev= std(x);

  13. Cont. • A function M-file name.m has the following general form: • function [ outarg1 , outarg2 , … ] = name ( inarg1 , inarg2 , … ) • % comments to be displayed with help ... • outarg1 = ... ; • outarg2 = ... ; ... • functionkeyword: The function file must start with the keyword function (in the function definition line).

  14. Cont. Input and output arguments: The input and output arguments (inarg1 , outarg1 , etc.) are ‘dummy’ variables, and serve only to define the function’s means of communication with the workspace. You can think of the actual input arguments being copied into the dummy input arguments when the function is called. So when stats(r) is called in the above example, the actual input argument r is copied into the input argument x in the function file.

  15. Cont. Multiple output arguments: If there is more than one output argument, the output arguments must be separated by commas and enclosed in square brackets in the function definition line. When a function is called with more than one output argument, the actual output arguments may be separated by commas or spaces. Naming convention for functions: Function names must follow the MATLAB rules for variable names. If the filename and the function definition line name are different, the internal name is ignored.

  16. Cont. • When you type help function_name,MATLAB displays the comment lines that appear between the function definition line and the first non-comment line. • Local variables: scope • Any variables defined inside a function are inaccessible outside the function. Such variables are called local variables .

  17. Cont. • Global variables: Variables which are defined in the base workspace are not normally accessibleinside functions, i.e. their scope is restricted to the workspace itself, unless they have been declared global , e.g. • global PLINK PLONK • If several functions, and possibly the base workspace, all declare particular variables as global, then they all share single copies of those variables. • MATLAB recommends that global variables be typed in capital letters, to remind you that they are global.

  18. Cont. The function isglobal(A) returns 1 if A is global, and 0 otherwise. The command who global gives a list of global variables. Use clear global to make all variables non-global, or clear x to make x non-global. Persistent variables: A variable in a function may be declared persistent . Local variables normally cease to exist when a function returns. Persistent variables, however, remain in existence between function calls.

  19. Cont. • In the following example, the persistent variable count is used to count how many times the function testis called: • function test • persistent count • if isempty(count) • count = 1 • else • count = count + 1 • end • Persistent variables remain in memory until the M-file is cleared or changed. e.g. clear test

  20. Cont. • The function mlock inside an M-file prevents the M-file from being cleared. A locked M-file is unlocked with munlock. The function mislockedindicates whether an M-file can be cleared or not. • Functions that do not return values: You might want to write a function that doesn’t return values. In that case you simply omit the output argument(s) and the equal sign in the function definition line. • function cube(x) • z = x * x * x; • disp(z)

  21. Cont. • Vector arguments: • the following function generates a vector of n random rolls of a die: • function d = dice( n ) • d = floor( 6 * rand(1, n) + 1 ); • When an output argument is a vector, it is initialized each time the function is called, any previous elements being cleared. Its size at any moment is therefore determined by the most recent call of the function.

  22. Cont. • If a function changes the value of any of its input arguments, the change is not reflected in the actual input argument on return to the workspace (unless the function is called with the same input and output argument—see below). • A function may be called with the same actual input and output argument. For example, the following function prune.m removes all the zero elements from its input argument: • function y = prune(x) • y = x(x ˜= 0); • You can use it to remove all the zero elements of the vector x as follows: • x = prune(x)

  23. Cont. A function may be called with all, some, or none of its input arguments. If called with no arguments, the parentheses must be omitted. You may not use more input arguments than appear in its definition. The same applies to output arguments. If you call a function with no output arguments, the value of the first one in the definition is returned.

  24. Cont. • There are times when a function may need to know how many input/ output arguments are used on a particular call. • In that case, the functions narginand nargout can be used to determine the number of actual input and output arguments. For example, • function y = foo(a, b, c); • disp( nargin ); • will display the number of input arguments present on each call of foo .

  25. 10.2.1 Subfunctions A function M-file may contain the code for more than one function. The first function in a file is the primary function, and is the one invoked with the M-file name. Additional functions in the file are called subfunctions, and are visible only to the primary function and to other subfunctions. Each subfunction begins with its own function definition line.

  26. 10.2.3 P-code files • The first time a function is called during a MATLAB session it is parsed (‘compiled’)into pseudocode and stored in memory to obviate the need for it to be parsed again during the current session. • The pseudocode remains in memory until you clear it with clear function_name. • You can use the pcode function to save the parsed version of an M-file for use in later MATLAB sessions, or by users from whom you want to hide your algorithms. For example, the command • pcode stats • Parses stats.m and stores the resulting pseudocode in the file named stats.p.

  27. cont

  28. cont

  29. Cont. function s = SquareRoot(a) if a > 0 tol = 0.00001; x = a / 2; while(1) y = (x + a / x) / 2; e = abs((y - x) / y); x = y; if e < tol, break, end end s = x; else s = 0; end

More Related