I have a large dataset and the following is a sample of it. The first column contains unique numbers while the second and third columns represnet the variables of interest.
dat = [4 32 24;
4 67 33;
4 80 40;
4 90 70;
9 22 10;
9 42 15;
9 52 30;
9 60 40]
I wrote the following code to caluclate the mean of the variables of interest for each unique number.
dat1=unique(dat(:,1))
datfinal = zeros(length(dat1),3)
datfinal(:,1)=dat1
for idx=1:length(dat1)
datfinal(idx,2)=mean(dat(dat(:,1)==dat1(idx),2))
datfinal(idx,3)=mean(dat(dat(:,1)==dat1(idx),3))
end
The code works and gives what I want but I am struggling in adjusting the loop to calculate the correlation coefficient (corr2) between columns 2 and 3 for each unqiue number separately. The result should be as follows
corr=[4 0.8243;
9 0.9293]
I appreciate your help.

 채택된 답변

Guillaume
Guillaume 2017년 5월 5일
편집: Guillaume 2017년 5월 5일

2 개 추천

Everything including finding the mean can be done in just three lines of code using findgroups and splitapply:
g = findgroups(dat(:, 1));
datmean = splitapply(@mean, dat, g)
datcorr = splitapply(@(rows) [rows(1) corr2(rows(:, 2), rows(:, 3))], dat, g)
edit: fixed missing closing bracket

댓글 수: 4

Technoguy
Technoguy 2017년 5월 5일
Thanks I relazied that this function is available only for recent veriosns of MATLAB and switched to a new veriosn but the last line of the code gives an error.
Guillaume
Guillaume 2017년 5월 5일
typo fixed.
The functions were introduced nearly two years ago. Not that recent.
Technoguy
Technoguy 2017년 5월 5일
Thank you it is now fully working.
Andrei Bobrov
Andrei Bobrov 2017년 5월 5일
+1

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

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2017년 5월 5일

댓글:

2017년 5월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by