Search code examples
matlabanonymous-functionfunction-handle

Deciphering a Function Handle Solution Found in http://stackoverflow.com/a/13135833/560821


So... I can understand matlab function handles and its purposes. But sometimes, when it gets too cryptic, I require help in further elaborating it. Take this example from the default MATLAB documentation, say:

f = @(x)x.^3-2*x-5;

I can also re-write it as:

function f(arg)
  arg.^3 - 2*arg - 5;
end   

Can anybody help out in deciphering the code below as previously mentioned from here? I don't need help in the default matlab functions. Just a little help in understanding the user-defined anonymous functions here..

applyToGivenRow = @(func, matrix) @(row) func(matrix(row, :))
applyToRows = @(func, matrix) arrayfun(applyToGivenRow(func, matrix), 1:size(matrix,1))'
% Example
myMx = [1 2 3; 4 5 6; 7 8 9];
myFunc = @sum;
applyToRows(myFunc, myMx)

Solution

  • applyToGivenRow = @(func, matrix) @(row) func(matrix(row, :))
    

    This is a function that creates another function, eg the following (as taken from the Question's example)

    applyToGivenRow(@myFunc,myMx)
    

    would evaluate to the function

    @(row) myFunc(myMx(row,:))
    

    Then

    applyToRows = @(func, matrix) arrayfun(applyToGivenRow(func, matrix), 1:size(matrix,1))'
    

    uses this applyToGivenRow function. Arrayfun loops through the vector you feed it (1:size(matrix,1)) and evaluates the function you feed (applyToGivenRow(func, matrix)) it for each value in the vector.

    The original author could have also shortened it down to

    applyToRows = @(func, matrix) arrayfun(@(row) func(matrix(row, :), 1:size(matrix,1))'
    

    Read the documentation about anonymous functions and arrayfun, and it should be easy to understand this.