Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

This week…

 Anonymous functions
 Function functions
 Global variables
 sprintf command
 Optional arguments (nargin, nargout, nargchk)

 Logical functions

EdaCelik© 164
Anonymous functions
are simple one-line functions created without the need for
an M-file. It provides a means of calling a function indirectly,
and/or defining variables easily.

fhandle = @(arg1, arg2, ...) expression

fhandle = @ function name

@ : to create function handle

EdaCelik© 165
Examples
>> sqr = @(x) x.^2; >> b=[2,3,4];
>> a=sqr(5) >> sqr(b) %you can also use it with an array
a= ans =
25 4 9 16

>> f1=@(x,y) x^2+y^2;


>> f1(3,4)
>> clear
ans =
>> f1=x^2+y^2
25
??? Undefined function or variable 'x'.

>> x=3; y=4;


>> f1=x^2+y^2
f1 = 166
25
EdaCelik©
Using function handles
function y = try1(x)
y = x.^2 +1;

fh = @try1;
fh(2.0) try1(2.0)
ans=
ans =
5.0 5.0

EdaCelik© 167
Example 2 -- Multiple Anonymous Functions

This example solves the following equation by combining two anonymous


functions:

To find the equivalent anonymous function for this expression, step by step:

@(x) (x.^2 + c*x + 1)

quad(@(x) (x.^2 + 2*x + 1), 0, 1)

g = @(c) (quad(@(x) (x.^2 + c*x + 1), 0, 1));

quad is a defined function in MATLAB to evaluate a


>> g(2)
ans = definite integral.
2.3333 q = quad(fun,a,b) to evaluate
168
Function functions
 are functions that operate on other functions
which are passed to it as input arguments

 The input argument may be:


 the handle of an anonymous
 the name of a built-in function
 the name of a M-file function
Example:

>> f1=@(x) x^2;


>> fplot (f1, [0 10])

EdaCelik© 169
Ex*: 3 different ways to use a
function function
>> myint1=quad(@(x) (x.^2 + 2*x + 1), 0, 1)
myint1 = 2.3333
>> f2=@(x) x.^2+2*x+1;
>> myint2=quad(f2,0,1)
myint2 = 2.3333
>> myint3=quad(@f3,0,1) %use @ if it is an .m file
myint3 = 2.3333

function a=f3(x)
a=x .^ 2 + 2 * x + 1;
EdaCelik© 170
* We will learn about the other function functions in KMU231
* Function functions are stored in the funfun folder in the MATLAB folder
in C drive under: toolbox -> compiler -> mcr -> matlab -> funfun

EdaCelik© 171
Global Variables
 If you want more than one function to share a single copy of a variable,
simply declare the variable as global in all the functions.
 Do the same thing at the command line if you want the base workspace to
access the variable.
 The global declaration must occur before the variable is actually used in a
function.
 Although it is not required, using capital letters for the names of global
variables helps distinguish them from other variables.

function h = falling(t)

global GRAVITY
h = 1/2*GRAVITY*t.^2;

Then interactively enter the statements

global GRAVITY
GRAVITY = 32;
y = falling((0:.5:5)');

EdaCelik© 172
KMU 134- Computer Programming

Optional/Variable
Arguments
Optional Arguments /Variable Argument Lists
 Many MATLAB functions support optional input arguments and output
arguments.

Ex: plot(Y)
plot(X1,Y1,...)
plot(X1,Y1,LineSpec,...)
plot(...,'PropertyName',PropertyValue,...)

 How do MATLAB functions know how many input and output arguments
are present, and how do they adjust their behavior accordingly?

 There are special functions that can be used by MATLAB functions to


get information about their optional arguments, report errors in those
arguments, or assign arguments if missing.

EdaCelik© 174
error—Display error message and abort the function producing the error.
This function is used if the argument errors are fatal.

warning—Display warning message and continue function execution.


This function is used if the argument errors are not fatal, and execution can
continue.

nargin—This function returns the number of actual input arguments that were
used to call the function.

nargout—This function returns the number of actual output arguments that were
used to call the function.

nargchk—This function returns a standard error message if a function is called


with too few or too many arguments.

EdaCelik© 175
nargin/nargout
Number of function input / output arguments

Insidethe body of a user-defined function, nargin


(nargout) returns the number of input (output)
arguments that were used to call the function.

nargin('fun') returns the number of declared inputs


for the M-file function 'fun'.

nargout('fun') returns the number of declared


outputs for the M-file function 'fun'.

The number of arguments is negative if the function has a


variable number of input arguments.

EdaCelik© 176
nargchk
Check number of input arguments. Generates a string containing a
standard error message if a function is called with too few or too many
arguments. The syntax of this function is:

message=nargchk(min_args, max_args, num_args);

where,
min_args: the minimum number of arguments,
max_args: the maximum number of arguments,
num_args: the actual number of arguments.

If the number of arguments is outside the acceptable limits, a standard


error message is produced. If the number of arguments is within
acceptable limits, then an empty string is returned.
EdaCelik© 177
Example
function f = foo(x, y, z)
error(nargchk(2, 3, nargin))

% on the command window:

>> foo(1,2,3,4)
??? Error using ==> foo
Too many input arguments.

>> foo(1) This is a standard


??? Error using ==> foo message
Not enough input arguments.

function f = foo(x, y, z)
msg=nargchk(2, 3, nargin);
error(msg)
EdaCelik© 178
Example 5.3
function [mag, angle] = polar_value(x,y)
% POLAR_VALUE Converts (x,y) to (r,theta)

msg = nargchk(1,2,nargin);
error(msg);

if nargin < 2
y = 0;
end

if x == 0 & y == 0
msg = 'Both x any y are zero: angle is meaningless!';
warning(msg);
end

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

if nargout == 2
angle = atan2(y,x) * 180/pi;
end

ATAN2 : Four quadrant inverse tangent.


% you are not responsible for this command, it is just useful in the scope of the example.
179
EdaCelik©
>> [mag angle] = polar_value
>> mag = polar_value(1,-1)
??? Error using ==> polar_value
Not enough input arguments.
mag =
1.4142
>> [mag angle] = polar_value(1,-1,1)
??? Error using ==> polar_value
>> [mag angle] = polar_value(0,0)
Too many input arguments.
Warning: Both x any y are zero: angle is
meaningless!
>> [mag angle] = polar_value(1)
> In polar_value at 13
mag =
mag =
1
angle =
0
0

>> [mag angle] = polar_value(1,-1)


angle =
mag =
0
1.4142

angle =
-45
EdaCelik© 180
Example (part of a code)

EdaCelik© 181
Note that a MATLAB function may be declared to have more output
arguments than are actually used, and this is not an error. The function
does not actually have to check nargout to determine if an output
argument is present.

function [z1, z2] = junk(x,y)


z1 = x + y;
z2 = x - y;
end

% This function can be called successfully


with one or two output arguments !!

» a = junk(2,1)
a =
3
» [a b] = junk(2,1)
a =
3
b =
1
EdaCelik© 182
Example
function [out1,out2] = humps(x)
if nargin==0,
x = 0:.05:1;
end

y = 1 ./ ((x-.3).^2 + .01) + 1 ./ ((x-.9).^2 + .04) - 6;

if nargout==2,
out1 = x; out2 = y;
else
out1 = y;
end

EdaCelik© 183
fplot(@humps,[0,2]); * Because humps is a M-file,
using inside the function fplot,
q = quad(@humps,0.5,1);
we need the @ sign.
title(['Area = ',num2str(q)]);
* If the function was defined on
the command window, we
wouldn’t need the @ sign, we
would just write the name of the
anonymous function.

Note: instead of the last line


above, try:

a=sprintf('Area= %3.2f',q);
title(a)

OR

title(sprintf('Area= %3.2f',q))
184
Ref: http://www.mathworks.com/ EdaCelik©

You might also like