Can somebody explain me this code?

1 次查看(过去 30 天)
jasmine
jasmine 2019-6-26
评论: Guillaume 2019-6-26
R = arrayfun (@(x) median(A(A(:,1)==x,2)==2), B);
(I've searched for 'arrayfun', but I still don't understand this completely)
Thank you.
  1 个评论
Rik
Rik 2019-6-26
What exactly don't you understand? Arrayfun applies the function to every element of your input, so for every element of B it runs that anonymous function.
Because you don't provide any other context it is difficult to explain it more than that.

请先登录,再进行评论。

回答(1 个)

Bob Thompson
Bob Thompson 2019-6-26
arrayfun is basically a for loop for all elements of an array.
This code is doing the following, starting from the outside:
1) Array fun is working through all elements of B. Each element is being represented as 'x.'
R = arrayfun (@(x) x, B);
2) The median values are being captured A values which are equal to 2.
median(A==2)
3) The range of A values is being limited to those in the second column.
A(:,2)
4) The range of A values is being limited to rows whose first column has a value equal to our element from B.
A(A(:,1)==x,2)
So, overall, this code is finding the median of values of A which are equal to 2, but only in the second column of rows whose first column value is equal to each respective element of B. Overall, all this code is going to do is determine whether 2 is a majority value of the subset of A, because the median command is receiving a logic array as an input, so all values will be either 1 or 0. For elements of R == 1, then 2 is a majority value for the corresponding element of B, and for elements of R == 0, then 2 is not a majority.
  5 个评论
Rik
Rik 2019-6-26
Just adding another note: median([true false]) returns true, so a strict majority is not required.
I think I would have used mean on the logical array (as that would allow more fine-grained control over the partitions), although I can imagine median might be a bit faster under some circumstances.
Guillaume
Guillaume 2019-6-26
It's not clear what B is, I suspect it might be the unique values of column 1 of A, in which case, I would have used:
group = findgroup(A(:, 1));
ismajority2 = splitapply(@(values) nnz(values == 2) >= numel(values)/2, A(:, 2), group);
which is a lot easier to understand. Even if B is not the unique values, I still would first partition A then use the splitapply (or accumarray if you're old fashioned).

请先登录,再进行评论。

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by