nX2 matrix. Random instances of 0,1,2... in column 1. Need to add all corresponding values of column 2 for each of 0,1,2... and create a matrix m X 2 where 1st column is 0,1,2.. and second column is the resultant sum of previous defined content.

조회 수: 1 (최근 30일)
Hi all,
I am a beginner in Matlab and most of my learnings come from kind answers to different problems in these sections.
I have a 11300 X 2 matrix which I imported from an excel file. Column 1 has 90 intsnaces of 0, 75 instances of 1, 87 instances of 2 and so on. So the number of instancs of 1,2,3….190 is random. For example:
0 0.16
0 0.23
. .
. .
1 9.34
1 0.34
. .
. .
190 4.5
Each instances has certain corresponding values in the column. I am looking to add up all the values of corresponding value of column 2 so that I can have the 191 X2 matrix looking as following:
0 2.7 % (ex:2.7 = 0.16 + 0.23 +.. all other values in second column corresponding to 0)%from above example
1 15.5 % (ex:15.5 = 9.34 + 0.34 +.. all other values in second column corresponding to 1)%from above example
2 0.6 % and so on as above
. .
190 9.8
Is there anyway I can get some help?

채택된 답변

Jonas
Jonas 2021년 5월 13일
편집: Jonas 2021년 5월 13일
dirty solution with for:
tbl=zeros(191,2);
for number=1:191
tbl(number,1)=number-1;
tbl(number,2)=sum(data(data(:,1)==number-1,2));
end
  댓글 수: 2
Tanmoy Sarkar
Tanmoy Sarkar 2021년 5월 17일
Thanks a lot. Exactly what I was looking for. For my learning, if you can please elaborate what the following line does in the loop,
Thanks.
tbl(number,2)=sum(data(data(:,1)==number-1,2))
Jonas
Jonas 2021년 5월 17일
편집: Jonas 2021년 5월 17일
data(:,1)==number-1
get logical index for the rows which contain the current number we are interested in
data(..,2)
get values from second column at the rows we specified in the mentioned positions
sum(..)
sum those values

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by