Finding average using two input condition from a table

9 vues (au cours des 30 derniers jours)
Harold Singh
Harold Singh le 22 Mar 2019
Commenté : Harold Singh le 25 Mar 2019
Hi, I hope someone can help me with this question. I'd like to find the average of the 3rd column of a table using conditions on the 1st and 2nd columns. For example, in the table below, I'd like to find the average z with x = 1 AND y = 1800 (this should be average of 1.5 and 2), and when x = 2, y = 1900 (1.4 alone), etc
x y z
1 1800 1.5
2 1900 1.4
3 2100 3
3 1900 1.1
1 1900 0.8
2 2700 1.2
3 1800 2

Réponse acceptée

Peter Perkins
Peter Perkins le 25 Mar 2019
Several ways to do this, including findgroups/splitapply, groupsummary, and varfun:
>> XYZ = [ ...
1 1800 1.5
2 1900 1.4
3 2100 3
3 1900 1.1
1 1900 0.8
2 2700 1.2
1 1800 2];
>> T = array2table(XYZ,'VariableNames',{'x' 'y' 'z'})
T =
7×3 table
x y z
_ ____ ___
1 1800 1.5
2 1900 1.4
3 2100 3
3 1900 1.1
1 1900 0.8
2 2700 1.2
1 1800 2
>> varfun(@mean,T,'GroupingVariables',{'x' 'y'})
ans =
6×4 table
x y GroupCount mean_z
_ ____ __________ ______
1 1800 2 1.75
1 1900 1 0.8
2 1900 1 1.4
2 2700 1 1.2
3 1900 1 1.1
3 2100 1 3
  1 commentaire
Harold Singh
Harold Singh le 25 Mar 2019
Peter, Many thanks. This works. Sure beats looping through the table, and computing the average.
Harold

Connectez-vous pour commenter.

Plus de réponses (1)

Harold Singh
Harold Singh le 22 Mar 2019
Sorry, I made a mistake with the table. The corrected table is:
x y z
1 1800 1.5
2 1900 1.4
3 2100 3
3 1900 1.1
1 1900 0.8
2 2700 1.2
1 1800 2

Catégories

En savoir plus sur Tables dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by