Advanced Functions


Function handles

function handle

 

 

 

Examples:

sinHandle = @sin;
natLog = @log;
xx = 0.1 : 0.01 : 2*pi;
yy1 = sinHandle(xx);
yy2 = natLog(xx);
plot(xx, yy1, 'b:', xx, yy2, 'r-.')

Anonymous function

 

 

Examples:

quadHandle1 = @(x)x.^2 + 2*x + 3;
quadHandle2 = @(p)(p – 1).^2;
disp(quadHandle1(2) + quadHandle2(-1))
plot(xx, quadHandle1(xx))

 

 

 


Passing a function to a function

Example:

function result = addNoise(values, noiseFctn)
% Modifies the values by using the given function to add "noise"
result = values + noiseFctn(values);

Using the addNoise function:

xx = -10 : 0.001 : 20;
myFctn = @(x)polyval([0.01, -0.1, -2, 5], x);
yy = myFctn(xx);
noise1 = addNoise(yy, @cos);
noise2 = addNoise(yy, @(x)0.5*sin(5*x));
plot(xx, yy, 'g-', xx, noise1, 'r--', xx, noise2, 'b-.')