代写 math matlab Programming MATLAB

Programming MATLAB
Paul Cotofrei
information management institute master of science in finance
2017

More Function Concepts
􏰁 Anonymousfunctions:simpleone-linefunctions
􏰁 Functionhandles:usedtorefertofunctions
􏰁 Functionfunctions:functionstowhichotherfunctionsare passed (in the form of function handles)
􏰁 Variablenumberofinputand/oroutputargumentstofunctions
􏰁 Subfunctions:includedintheMfileofanotherfunction
􏰁 Recursivefunctions:functionsthatcallthemselves

Anonymous functions
􏰁 Twomethodstodefineuser-definedfunctions 􏰁 M-file (using function keyword)
􏰁 Anonymous
􏰁 Anonymousfunctionsarereallysimple,shortfunctionsthatfiton
one line
􏰁 Generalform:
fnhanvar = @ (input arguments) functionbody
􏰁 Theinputargumentsandfunctionbodyaresimilartoother functions, except that the body is just one expression
􏰁 the@returnsthehandleofthefunction,whichisawayof referring to the function
􏰁 thevariableontheleftoftheassignmentstoresthefunction handle

Calling Anonymous Functions
􏰁 Callingthefunctionisaccomplishedbyusingthefunction handle, and passing arguments:
fnhanvar(input arguments)
􏰁 Example of an anonymous function that calculates the area of a circle:
􏰁 Calling:
» cirarea = @ (radius) pi * radius .^2;
» cirarea(4)
ans =
50.2655
» areas = cirarea(1:4)
areas =
3.1416 12.5664 28.2743 50.2655
􏰁 Anadvantageofanonymousfunctionsisthatyoudon’thaveto store them in an M-file
􏰁 However,itisusefultostoregroupsofrelatedanonymous functions in MAT-files

Multiple/No Input Parameters
􏰁 Let be the mathematical function f(x) = e−0.5xsin(x) 􏰁 Anonymous:
􏰁 To include parameters (e.g. f(x) = e−axsin(bx))
􏰁 Method 1
􏰁 Method 2
􏰁 Iftherearen’tanyinputarguments,youstillhavetohaveempty () in the function definition and the function call
» f = @(x) exp(-0.5*x).*sin(5*x);
» a = 0.5; b = 5;
» f = @(x) exp(-a*x).*sin(b*x);
» f = @(x,a,b) exp(-a*x).*sin(b*x);
» prtran = @() fprintf(’%.2f\n’,rand);
» prtran()
0.95
» prtran
prtran =
@ () fprintf(’%.2f\n’,rand)

Another Example

Function Handles
􏰁 functionhandle-adatatypethatallowsthereferencingandevaluation of a function
􏰁 Functionhandlescanbecreatedforallfunctions,notjustanonymous functions
fnhanvar = @fnname
􏰁 fnname can be the name of a built-in or user-defined function
􏰁 Thehandlecanthenbeusedtocallthefunction: fnhanvar(input arguments)
instead of
fnname(input arguments)
􏰁 Functionhandlesmakeitpossibletopassfunctionstootherfunctions to use – instead of passing the name of a function, you pass its handle
􏰁 Afunctionthatreceivesafunctionhandleasanargumentiscalleda function function
􏰁 Thefunctionhandlethatispassedcanbeofabuilt-infunction, anonymous function, or user-defined function

Example
􏰁 Defineauser-definedfunction(functionfunction)andsaveitinmyfunc.mfile
􏰁 Letbethefollowinguser-definedfunctionpoly:
􏰁 Createfunctionhandles
􏰁 Callthefunctionmyfuncbypassingavectorandfunctionhandle:
function out = myfunc(x, call) out = call(x);
end
function val = poly(x) val = x.^3 – 4 * x + 5;
end
» fh_poly1 = @poly; % Function handle for user-defined function poly
» fh_poly2 = @(x) x.^2 – 3; % Function handle for an anonymous function » fn_cos = @cos; % Function handle for a built-in function
» x » y y=
» y y=
= 3:.5:6;
= myfunc(x, fn_poly1)
20.0000 33.8750 53.0000 78.1250 110.0000 149.3750 197.0000 = myfunc(x, fn_poly2)
6.0000 9.2500 13.0000 17.2500 22.0000 27.2500 33.0000 » myfunc(x, fh_cos)
ans =
-0.9900 -0.9365 -0.6536 -0.2108 0.2837 0.7087 0.9602 » myfunc(x, @sum)
ans =
31.5000

Subfunctions
􏰁 Afunctioncaninclude,atitsend,thedefinitionsofother functions, referred to as subfunctions
􏰁 Thesubfunctionscanappearinanyorderandeachcanbe called by any of the other ones within the primary function
% alternative version of rms.m
function [r,m] = rms(x)
r = rmsq(x); % root-mean-square
m = mav(x); % mean absolute value
end
function y = rmsq(x)
y = sqrt(sum(abs(x).^2) / length(x));
end
function y = mav(x)
y = sum(abs(x)) / length(x);
end

Recursive Functions
􏰁 Recursioniswhensomethingisdefinedintermsofitself
􏰁 Factorialexample:
􏰁 Iterativedefinition:n!=1∗2∗···∗n
􏰂0! = 1 basecase
􏰁 Recursive definition: n! = (n − 1)! ∗ n general case
􏰁 Witharecursivedefinition,thereisalwaysageneralcase
which is recursive, but also a base case that stops the recursion
􏰁 Recursivefunctionsarefunctionsthatcallthemselves
􏰁 Sometimeseitheriterationorrecursioncanbeusedto implement a solution to a problem

Code for recursive factorial
􏰁 Afunctionthatimplementstherecursivedefinitionhasan if-else statement to choose between the general and base cases:
function facn = fact(n)
% fact recursively finds n!
% call: fact(n)
if n == 0
facn = 1;
else
facn = n * fact(n-1);
end end
» fact(0)
ans =
1
» fact(5)
ans = 120
» fact(-2) % WARNING: infinite loop !
% fact(-2) calls fact(-3) which calls fact(-4) ….

Example: Fibonacci numbers
 0 f(n) = 1
 f(n−1)+f(n−2)
if n = 0 if n = 1 ifn≥2
function y = fibo(n)
if n == 0
y = 0;
elseif n == 1
y = 1; else
y = fibo(n-1) + fibo(n-2);
end
end
y = [];
for n = 1:10
y = [y fibo(n)];
end
disp(y)
0 1 1 2 3 5 8 13 21 34

Example: binomial coefficients

Example: Sierpinsky Gasket

Code for Sierpinsky Gasket