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