Mean of values in acolumn depending on VARYING values of another column

조회 수: 2 (최근 30일)
Freya
Freya 2023년 10월 4일
댓글: Freya 2023년 10월 5일
Hi, I would like to calculate the mean of values in a coulmn, based on the values in another column. However, different from other questions asked previously on this forum, the values in the second column I need to use are not specific, but change. Please see attached file and hopefully it will be easier to get what I mean. Maybe I need to use a for loop running through all the values of the second column? Thank you!

채택된 답변

Dyuman Joshi
Dyuman Joshi 2023년 10월 4일
in =readmatrix('Book2.xlsx');
disp(in)
1 1 2 2 3 1 4 2 5 3 6 1 7 2 8 4 9 1 10 5 11 6 12 5 13 5 14 4 15 6 16 3 17 6 18 2 19 1 20 5 21 3 22 2 23 4
out = accumarray(in(:,2),in(:,1),[],@mean)
out = 6×1
7.6000 10.6000 14.0000 15.0000 13.7500 14.3333
  댓글 수: 14
Dyuman Joshi
Dyuman Joshi 2023년 10월 5일
Use the first output of unique()
format longg
in = readmatrix('Book3.xlsx');
[out1,~,idx] = unique(in(:,2))
out1 = 535×1
1.0e+00 * 1000227087 1000227106 1000594972 1000594973 1000594974 1000594975 1000594976 1000594977 1000594978 1000594979
idx = 13354×1
1 2 3 4 5 6 7 8 9 10
out2 = accumarray(idx,in(:,1),[],@mean)
out2 = 535×1
0.453491780924332 0.240638995346782 0.366433792273591 0.155783195173162 0.359111503883272 0.334567544249371 0.234826867085867 0.335793779361822 -0.0249592514078918 0.260758590555741
Concatenate them horizontally to get them in the same array
out = [out1 out2];

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Ken Garrard
Ken Garrard 2023년 10월 4일
You do not need a for loop.
Assumming that your data is in an Nx2 variable named, mydata.
% Select rows matching criteria in column 2
% For example, values in column 2 greater than one and less than five
hits = mydata(:,2) > 1 & mydata(:,2) < 5;
% Mean of values from column 1
mean(mydata(hits,1))
ans =
12.7273

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by