Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
61 views

MATLAB and LABView - Chapter 5

This document discusses user-defined functions in MATLAB. It introduces MATLAB functions and how they differ from scripts by receiving input arguments and returning output arguments. It covers variable passing in MATLAB using pass-by-value, optional arguments, sharing data using global memory, and function functions which allow functions as input arguments. Examples are provided to illustrate each concept.

Uploaded by

vinh quoc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

MATLAB and LABView - Chapter 5

This document discusses user-defined functions in MATLAB. It introduces MATLAB functions and how they differ from scripts by receiving input arguments and returning output arguments. It covers variable passing in MATLAB using pass-by-value, optional arguments, sharing data using global memory, and function functions which allow functions as input arguments. Examples are provided to illustrate each concept.

Uploaded by

vinh quoc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

MATLAB and LabVIEW

Chapter 5
User-Defined Functions

Nguyen Huu Cuong, PhD.


5.1 Introduction to MATLAB functions
• Script files are just collections of MATLAB statements that are stored in a file.
• When a script file is executed, the result is the same as all of the commands had
been typed directly into the Command Window.
• Script files share the Command Window’s workspace.
• A script file has no input arguments and returns no results
• Script files can communicate with other script files through the data left behind
in the workspace.
5.1 Introduction to MATLAB functions
• A MATLAB function is a special type of M-file that runs in its own independent
workspace.
• It receives input data through an input argument list, and returns results to the
caller through an output argument list.
• The general form of a MATLAB function is

• MATLAB function should be place in file with the same name as the function,
and the extent “.m”.
• A function may be invoked by typing its name directly in the Command Window,
or by including it in a script file or another function.
5.1 Introduction to MATLAB functions
• Execution begins at the top of the function and ends when either a return
statement, and end statement, or the end of the function is reached.
• The initial comment lines in a function serve a special purpose.
• The first comment line after the function statement is called the H1 comment
line. It should always contain a one-line summary of the purpose of the
function. The special significance of this line is that it is searched and displayed
by the lookfor command.
• The remaining comment lines from the H1 line until the first blank line or first
executable statement are displayed by the help command. They should be
contain a brief summary of how to use the function.

• Example of user-defined function. Function dist2 calculates the distance


between points (x1, y1) and (x2, y2) in a Cartesian coordinate system.
test_dist2
help dist2
lookfor distance
5.2 Variable passing in MATLAB
• MATLAB programs communicate with their functions using a pass-by-value
scheme.
• When a function call occurs, MATLAB makes a copy of the actual arguments and
passes them to the function.
• This copying is very significant. If the function modifies the input arguments, it
won’t affect the original data in the caller.
5.2 Variable passing in MATLAB

function out = sample(a,b,c)


fprintf('In sample: a = %f, b = %f %f\n',a,b);
a = b(1) + 2*a;
b = a .* b;
out = a+ b(1);
fprintf('In sample: a = %f, b = %f %f\n',a,b);

a = 2; b = [6 4];
fprintf('Before sample: a = %f, b = %f %f\n',a,b);
out = sample(a,b);
fprintf('After sample: a = %f, b = %f %f\n',a,b);
fprintf('After sample: out = %f\n', out);

>> test_sample
Before sample: a = 2.000000, b = 6.000000 4.000000
In sample: a = 2.000000, b = 6.000000 4.000000
In sample: a = 10.000000, b = 60.000000 40.000000
After sample: a = 2.000000, b = 6.000000 4.000000
After sample: out = 70.000000
5.2 Variable passing in MATLAB
5.2 Variable passing in MATLAB

function [x, y] = polar2rect(r,theta)


%POLAR2RECT Convert rectangular to polar coordinates
% ------

x = r * cos(theta * pi/180);
y = r * sin(theta * pi/180);

function [r, theta] = rect2polar(x,y)


%RECT2POLAR Convert rectangular to polar coordinates
% -------

r = sqrt( x.^2 + y .^2 );


theta = 180/pi * atan2(y,x);
5.2 Variable passing in MATLAB
5.2 Variable passing in MATLAB
5.3 Optional arguments
• Many MATLAB functions support optional input arguments and output
arguments.
• For example, the plot function with as few as two or as many as seven input
arguments; the function max supports either one or two output arguments.
• There are special functions that can be used to get information about optional
arguments and to report errors in those arguments:
 nargin – return the number of actual input arguments
 nargout – return the number of actual output arguments
 nargchk – return a standard error message if a function is called with too
few or too many arguments.
 error – display error message and abort the function producing the error.
 warning – display warning and continue function execution.
 inputname – return the actual name of the variable that corresponds to a
particular argument number
5.3 Optional arguments
• Function nargchk generates a string containing a standard error message if a
function is called with too few or too many arguments.
message = nargchk(min_agrs, max_args, num_args);
• If the number of arguments is outside the acceptable limits, a standard error
message is procedure.
• If the number of argument is within acceptable limits, then an empty string is
returned.

• Function inputname returns the name of the actual argument used when a
function is called.
name = inputname(argno);
• If the argument is a variable, then its name is returned. If the argument is an
expression, then this function will return an empty string.
function myfunc(x,y,z)
name = inputname(argno);
disp(['The second argument is named ' name]);
5.3 Optional arguments
function [mag, angle] = polar_value(x,y)
%POLAR_VALUE Converts (x,y) to (r,theta)

% Check for a legal number of input arguments.


msg = nargchk(1,2,nargin);
error(msg);
% If the y argument is missing, set it to 0.
if nargin < 2
y = 0;
end
% Check for (0,0) input arguments, and print out
% a warning message.
if x == 0 & y == 0
msg = 'Both x any y are zero: angle is meaningless!';
warning(msg);
end
% Now calculate the magnitude.
mag = sqrt(x.^2 + y.^2);
% If the second output argument is present, calculate
% angle in degrees.
if nargout == 2
angle = atan2(y,x) * 180/pi;
end
5.4 Sharing data using global memory
• Global memory is a special type of memory that can be access from any
workspace.
• If a variable is declared to be global in a function, then it will be placed in the
global memory instead of the local workspace.
• If the same variable is declared to be global in another function, the that
variable will refer to the same memory location as the variable in the first
function.
• A global variable is declared with the global statement.

global var1 var2 var3 …


5.4 Sharing data using global memory
Example – Random number generator
• Most engineering designs are tested by running simulations of the operation of
the system before it is ever built. These simulations involve creating
mathematical models of the behavior of the system, and feeding the models a
realistic string of input data. If the models respond correctly to the simulated
input data, then we can have reasonable confidence that the real-world system
will respond correctly to the real-world input data.
• This equation defines the next value in a series by multiplying the previous value
by a linear equation and then taking the modulus of the resulting value.

• The random number will be based on the equation


5.4 Sharing data using global memory

function seed (new_seed)


global iseed
new_seed = round(new_seed);
iseed = abs(new_seed);
5.4 Sharing data using global memory
function ran = random0(m,n)
%RANDOM0 Generate uniform random numbers in [0,1)

% Declare global values


global iseed % Seed for random number generator
% Check for a legal number of input arguments.
msg = nargchk(1,2,nargin);
error(msg);
% If the n argument is missing, set it to m.
if nargin < 2
n = m;
end
% Initialize the output array
ran = zeros(m,n);
% Now calculate random values
for ii = 1:m
for jj = 1:n
iseed = mod(8121*iseed + 28411, 134456 );
ran(ii,jj) = iseed / 134456;
end
end
5.5 Function functions
• Function functions is the way that MATLAB gives to a function whose input
argument include the names of other functions.
• Function fzero locates a zero of the function is passed to it.
fzero(fun,x)
• Function eval evaluates a character string as through it had been typed in the
Command Window
eval(string)
• Function feval evaluates a named function defined by a M-file at a specified
input value
feval(fun,value)
5.5 Function functions
Example – Creating a function function
• Create a function function that will plot any MATLAB function of a single
variable between specified starting and ending values.
5.5 Function functions
function quickplot(fun,xlim)
%QUICKPLOT Generate quick plot of a function

% Check for a legal number of input arguments.


msg = nargchk(2,2,nargin);
error(msg);
% Check the second argument to see if it has two
% elements. Note that this double test allows the
% argument to be either a row or a column vector.
if ( size(xlim,1) == 1 & size(xlim,2) == 2 ) | ...
( size(xlim,1) == 2 & size(xlim,2) == 1 )
% Ok--continue processing.
n_steps = 100;
step_size = (xlim(2) - xlim(1)) / n_steps;
x = xlim(1):step_size:xlim(2);
y = feval(fun,x);
plot(x,y);
title(['\bfPlot of function ' fun '(x)']);
xlabel('\bfx');
ylabel(['\bf' fun '(x)']);
else
% Else wrong number of elements in xlim.
error('Incorrect number of elements in xlim.');
end
5.5 Function functions

>> quickplot('cos',[-2*pi 2*pi])

Plot of function cos(x)


1

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
-8 -6 -4 -2 0 2 4 6 8
x
5.6 Subfunctions, private functions, and nested functions
• Subfunctions are often used to implement “utility” calculations for a main function.

function [avg, med] = mystats(u)


% MYSTATS Find mean and median with internal
functions.
% Function MYSTATS calculates the average and
median
% of a data set using subfunctions.
n = length(u);
avg = mean(u,n);
med = median(u,n);

function a = mean(v,n)
% Subfunction to calculate average.
a = sum(v)/n;

function m = median(v,n)
% Subfunction to calculate median.
w = sort(v);
if rem(n,2) == 1
m = w((n+1)/2);
else
m = (w(n/2)+ w(n/2+1))/2;
end
5.6 Subfunctions, private functions, and nested functions
• Private functions are functions that reside in subdirectories with the special name
private.
• Nested functions are functions that are defined entirely within the body of
anotherfunction, called the host function.
5.6 Subfunctions, private functions, and nested functions
function res = test_nested_1
% This is the top level function.
% Define some variables.
a = 1; b = 2; x = 0; y = 9;
% Display variables before call to fun1
fprintf('Before call to fun1:\n');
fprintf('a, b, x, y = %2d %2d %2d %2d\n', a, b, x, y);
% Call nested function fun1
x = fun1(x);
% Display variables after call to fun1
fprintf('\nAfter call to fun1:\n');
fprintf('a, b, x, y = %2d %2d %2d %2d\n', a, b, x, y);
% Declare a nested function
function res = fun1(y)
% Display variables at start of call to fun1
fprintf('\nAt start of call to fun1:\n');
fprintf('a, b, x, y = %2d %2d %2d %2d\n', a, b, x, y);
y = y + 5;
a = a + 1;
res = y;
% Display variables at end of call to fun1
fprintf('\nAt end of call to fun1:\n');
fprintf('a, b, x, y = %2d %2d %2d %2d\n', a, b, x, y);
end % function fun1
end % function test_nested_1

You might also like