How to find the mean of one column based on the value in another column

15 ビュー (過去 30 日間)
Catherine Branter
Catherine Branter 2018 年 10 月 30 日
編集済み: DGM 2021 年 5 月 13 日
I want to find the mean of the values in the second column only for the rows which have the value 3 in column 10 I have tried mean = mean(data(data(:,10)==3,8))

採用された回答

Bruno Luong
Bruno Luong 2018 年 10 月 30 日
編集済み: Bruno Luong 2018 年 10 月 30 日
You command is correct (beside using 8th column instead of 2nd) BUT:
Don't name your (output) variable MEAN, you will have conflict later when using function MEAN.
  6 件のコメント
Swazi Sharma
Swazi Sharma 2021 年 5 月 13 日
Hey guys! If I want to do the same thing, but change the parameter from 3 to a word (for example: "January"). Can i just change the 3 to January, or do I have to change other bits in code?
DGM
DGM 2021 年 5 月 13 日
編集済み: DGM 2021 年 5 月 13 日
Comparisons between words don't really work the same way, and the approach depends on the variable type.
For character vectors:
myword = 'apple';
myword == 'orange' % results in error if the words aren't the same size
strcmpi(myword,'orange') % this would be a valid comparison
If you don't need case-insensitivity, use strcmp() instead.
If the variables are actual strings (in double quotes), the behavior is a bit different.
myword = "apple"
myword == "orange" % this actually does work with strings
strcmpi(myword,"orange") % this still works with either
Similarly, the indexing expressions you use to apply this comparison would depend entirely on the type of array in which these variables exist. Practical arraying of strings and character vectors vary, so I can't guess what you have.
If I presume that you're using a cell array (note the case-insensitive behavior of strcmpi()):
A = {12 56 'orange';
64 46 'apple';
32 36 'Peach';
64 16 'apple';
32 26 'peAch';
64 41 'apple';
32 72 'peach';
64 26 'apple';
32 86 'peach';
34 48 'banana'}
% mean of col2 for rows where col3 is 'peach'
mn = mean([A{strcmpi(A(:,3),'peach'),2}])
ans =
55
Otherwise, you'll have to adapt this to whatever array type you're using.

サインインしてコメントする。

その他の回答 (1 件)

Matt J
Matt J 2018 年 10 月 30 日
mean(data(data(:,10)==3,2))
  5 件のコメント
Catherine Branter
Catherine Branter 2018 年 10 月 30 日
編集済み: Catherine Branter 2018 年 10 月 30 日
this is the error i get:
Index exceeds the number of array elements (0).
Error in ML_Coursework (line 16) output = mean(data(data(:,10)==3,2))
Bruno Luong
Bruno Luong 2018 年 10 月 30 日
Catherine Branter : look at my answer bellow

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by