@(x)sum(x.IsBranch)

2 次查看(过去 30 天)
Salad Box
Salad Box 2019-1-14
编辑: Guillaume 2019-1-14
Hi,
As I tried to understand the example line by line, I am stuck at below:
numBranches = @(x)sum(x.IsBranch);
mdlDefaultNumSplits = cellfun(numBranches, MdlDefault.Trained);
To my understanding, MdlDefault.Trained is a 10x1 cell (10-fold). Shown below.
1.png
Each cell is an independent regression tree containing all the properties shown below.
2.png
from the above two lines of codes, function @(x)sum(x.IsBranch) has an x in the function, to my understanding here x is MdlDefault.Trained. However, MdlDefault.Trained has so many properties. This function would look like:
(MdlDefault.Trained)sum(MdlDefault.Trained.IsBranch).
What does above line mean? I feel it is difficult to understand.

采纳的回答

Guillaume
Guillaume 2019-1-14
编辑:Guillaume 2019-1-14
cellfun is just a convenient way to iterate over all the elements of a cell array. It pass each element in turn to the function it is given. In your particular case, the function is an anonymous function with one input (called x, the name doesn't matter) which returns the sum of x.IsBranch. If we were to deconstruct that cellfun line, it would be equivalent to:
mdlDefaultNumSplits = zeros(size(MdlDefault.Trained)); %cellfun automatically create the output array
for iter = 1:numel(mdlDefaultNumSplits) %cellfun iterates over each element
x = MdlDefault.Trained{iter}; %and dereference the cell content
%then it calls the function which in this case does
z = sum(x.IsBranch);
%and put the output of the anonymous function in the output matrix:
mdlDefaultNumSplits(iter) = z;
end
So x is the content of a single cell of MdlDefault.Trained which according to your first screenshot is a CompactRegressionTree. I don't have the stats toolbox so can check what IsBranch is. Since it's not listed as a property, I assume it's a function of CompactRegressionTree. Probably one that returns a logical array.

更多回答(1 个)

Salad Box
Salad Box 2019-1-14
Anonymous Functions
You can create handles to anonymous functions. An anonymous function is a one-line expression-based MATLAB function that does not require a program file. Construct a handle to an anonymous function by defining the body of the function, anonymous_function, and a comma-separated list of input arguments to the anonymous function, arglist. The syntax is:
h = @(arglist)anonymous_function

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by