2

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)
Community
  • 1
  • 1
Denz Choe
  • 81
  • 2
  • 7

1 Answers1

3
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.

Denz Choe
  • 81
  • 2
  • 7
Gunther Struyf
  • 11,158
  • 2
  • 34
  • 58