A function handles in Octave is defined as the example below.
f = @sin;
From now on, calling function f(x)
has the same effect as calling sin(x)
. So far so good. My problem starts with the function below from one of my programming assignments.
function sim = gaussianKernel(x1, x2, sigma)
The line above represents the header of the function gaussianKernel
. This takes three variables as input. However, the call below messes up my mind because it only passes two variables and then three while referring to gaussianKernel
.
model = svmTrain(X, y, C, @(x1, x2) gaussianKernel(x1, x2, sigma));
Shouldn't that be simply model = svmTrain(X, y, C, @gaussianKernel(x1, x2, sigma));
? What is the difference?
You didn't provide the surrounding code, but my guess is that the variable sigma
is defined in the code before calling model = svmTrain(X, y, C, @(x1, x2) gaussianKernel(x1, x2, sigma));
. It is an example of a parametrized anonymous function that captures the values of variables in the current scope. This is also known as a closure. It looks like Matlab has better documentation for this very useful programming pattern.
The function handle @gaussianKernel(x1, x2, sigma)
would be equivalent to @gaussianKernel
. Using model = svmTrain(X, y, C, @gaussianKernel(x1, x2, sigma));
might not work in this case if the fourth argument of svmTrain
is required to be a function with two input arguments.