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 Center および File ExchangeVariables についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by