Professional Documents
Culture Documents
ITW5
ITW5
ITW5
Workshop
Functions
Syntax for Function Definition
function [outputArg1,outputArg2] = untitled1(inputArg1,inputArg2)
outputArg1 = inputArg1;
outputArg2 = inputArg2;
end
Create Functions in Files
function f = fact(n)
f = prod(1:n);
end
y = 2;
p = fact(n)/fact(n-r);
DOUBLE CAUTION! The functions in the example are local to the script
end
function f = fact(n)
f = prod(1:n);
end
Add Help for Your Program
function c = addme(a,b)
% ADDME Add two values together.
% C = ADDME(A) adds A to itself.
% C = ADDME(A,B) adds A and B together.
% See also SUM, PLUS.
disp("no.s of args: " + nargin) INFO: function variables can be accessed in debugging mode.
switch nargin nargin and nargout indicate how many input or output arguments,
case 2 respectively, a user has supplied.
c = a + b;
case 1
c = a + a;
otherwise
c = 0;
end
Persistent Variables
function findSum(inputvalue)
persistent SUM_X
if isempty(SUM_X)
SUM_X = 0;
end
SUM_X = SUM_X + inputvalue;
disp(SUM_X)
Global Variables
function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;
global GRAVITY
GRAVITY = 32;
y = falling((0:.1:5)’);
s = @(x) sin(1./x);
s = @(x) sin(1./x);
y = s(pi)
y = 0.3130
range = [0.01,0.1];
fplot(s,range)
variable formul
a
Variables in the Expression
a = 1.3;
b = .2;
c = 30;
parabola = @(x) a*x.^2 + b*x + c;
The values persist within the function handle even if
clear a b c you clear the variables
x = 1;
y = parabola(x)
y =
31.5000
Functions with Multiple Inputs
myfunction = @(x,y) (x^2 + y^2 + x*y);
x = 1;
y = 10;
z = myfunction(x,y)
z = 111
Find Number of Function Arguments
function c = addme(a,b) function [result,absResult] =
switch nargin addme2(a,b)
case 2 switch nargin
case 2
c = a + b;
result = a + b;
case 1 case 1
c = a + a; result = a + a;
otherwise otherwise
c = 0; result = 0;
end end
if nargout > 1
absResult = abs(result);
end
What Is a Function Handle?
A function handle is a MATLAB data type that stores an association to a function. Indirectly
calling a function enables you to invoke the function regardless of where you call it from.
Passing a function to another function (often called function functions). For example, passing
a function to integration and optimization functions, such as integral and fzero.
Specifying callback functions (for example, a callback that responds to a UI event or interacts
with data acquisition hardware).
Constructing handles to functions defined inline instead of stored in a program file
(anonymous functions).
Calling local functions from outside the main function.
Creating Function Handles…
To create a handle for a function, precede the function name with an @ sign.
f = @myfunction;
Call a function using a handle the same way you call the function directly.
function y = computeSquare(x)
y = x.^2;
end
f = @computeSquare;
a = 4;
b = f(a)
b =
16
Creating Function Handles
h = @ones;
a = h()
a =
1
Without the parentheses, the assignment creates another function handle.
a = h
a =
@ones