NSCS 344, Week 8: Concepts

Table of Contents

Function handles

Function handles are a way of turning functions into variables. For example, let's turn the "mean" function into a function handle.
fHandle = @(x) mean(x)
fHandle = function_handle with value:
@(x)mean(x)
Now we can get the mean of a vector by typing
fHandle([1 2 3])
ans = 2
We can also assign the handle to another variable name like this
H = fHandle;
Then
H([1 2 3])
ans = 2
We can also have more than one input to a function handle like this
fHandle = @(x, y) mean(x, y)
fHandle = function_handle with value:
@(x,y)mean(x,y)
where the second input tells us the dimension to take the mean over
fHandle([1 2 3], 1)
ans = 1×3
1 2 3
fHandle([1 2 3], 2)
ans = 2