Classify rows of a matrix
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Pooneh Shah Malekpoor
le 16 Mar 2021
Commenté : the cyclist
le 16 Mar 2021
Hello
I want to know how it is possible to define a condition as if the numbers at the second column of some rows of a matrix are equal to each other and at the same time if the numbers at the third column of the same rows are equal to each other , then classify the first column numbers of those rows and calculate their mean values...in simple words, consider matrix A as:
A=[0.9 20.1 0.3;
0.8 19 1;
0.57 20.1 0.3;
0.7 20.1 0.4;
1 19 1]
I need a code to calculate the mean value of 0.9 and 0.57 as the numbers in second and third column of row 1 and 3 are the same. It should also calculate the mean of 0.8 and 1 as the numbers in second and third column of row 2 and 5 are the same.
Any help is highly appriciated.
Bests
0 commentaires
Réponse acceptée
the cyclist
le 16 Mar 2021
A=[0.9 20.1 0.3;
0.8 19 1;
0.57 20.1 0.3;
0.7 20.1 0.4;
1 19 1]
[uniqueA23, ~, subs] = unique(A(:, [2 3]), 'rows');
meanA1 = accumarray(subs, A(:,1), [], @mean);
output = [meanA1, uniqueA23]
2 commentaires
the cyclist
le 16 Mar 2021
Sure, but you'll probably need to read and understand some of the documentation of unique() and accumarray() to get a complete understanding.
The first line is identifying the rows of A where columns 2 and 3 are the same. The input
A(:, [2 3])
is all rows of A, but only the 2nd and 3rd column. The input 'rows' indicates that we want the unique rows, not the unique elements.
The output
uniqueA23
is the those unique rows. The output
subs
keeps track of which rows in the original matrix correspond to the unique ones.
The second line uses the powerful accumarray function -- "accumulate array". In this case, "accumulate" means "take groups of rows -- defined by subs -- and perform an operation on them". In this case, the input is the first column of A, and we have defined that operation to be the mean.
Plus de réponses (0)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!