Effacer les filtres
Effacer les filtres

How to find average of certain cells in a column if it's associated with another cells in another column?

4 vues (au cours des 30 derniers jours)
What if you also want to take the average of other values associated with other numbers in column 2. Let's say you have:
A = [1, 1
2, 1
3, 2
4, 2
5, 2
6, 3
7, 3];
where in column 2, I arranged the numbers in order, so column 2 has [1,1,2,2,2,3,3]. There are three unique numbers, {1,2,3}, where 1 appears 2 times; 2 appears 3 times; 3 appears 2 times.
I want to find the average of all numbers in column 1 that are associated with 1 in column 2; all numbers in column 1 associated with 2 in column 2; all numbersin column 1 associated with 3 in column 2. So I make a new array:
unique_column_2 = unique(A{:,2});
avg_column_1 = zeros(length(unique_column_2),1);
After this I'm stuck, I tried many if loops and I would get NaN for every cell in avg_column_1. I tried your synax up there and I still get NaN.
All I want is an array to compute the average of values that are associated with certain values on the other columns. Thank you so much if you can help!

Réponses (1)

Ameer Hamza
Ameer Hamza le 23 Nov 2020
You can use splitapply()
A = [1, 1
2, 1
3, 2
4, 2
5, 2
6, 3
7, 3];
[grps, vals] = findgroups(A(:,2));
out = [splitapply(@mean, A(:,1), grps) vals]

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by