Effacer les filtres
Effacer les filtres

Can somebody explain me this code?

1 vue (au cours des 30 derniers jours)
jasmine
jasmine le 26 Juin 2019
Commenté : Guillaume le 26 Juin 2019
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 commentaire
Rik
Rik le 26 Juin 2019
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.

Connectez-vous pour commenter.

Réponses (1)

Bob Thompson
Bob Thompson le 26 Juin 2019
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 commentaires
Rik
Rik le 26 Juin 2019
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 le 26 Juin 2019
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).

Connectez-vous pour commenter.

Catégories

En savoir plus sur Variables dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by