Sum nX2 matrix

조회 수: 1 (최근 30일)
Gudmund Hjelmqvist
Gudmund Hjelmqvist 2015년 11월 3일
답변: Stephen23 2015년 11월 6일
Hi
I'm new to matlab. I want to sum elements in a matrix nx2
1 132
1 8989
2 898
2 9898
2 89898
3 90909
3 90909
In my matrix first column is Var1 and second Var2 I want to sum all elements with the same Var1 and create a matrix 12*1 where all elements Var1=x are summed togehter.

채택된 답변

Tushar Sinha
Tushar Sinha 2015년 11월 5일
Hi Gudmund,
Let's call the matrix, M. Let's find all the entries in column 2, corresponding to the value of 1 in column 1. You can use logical indexing ( to do that as illustrated below:
>> M(M(:,1)==1,2)
ans =
132
8989
The above command gives you all the entries in the second column corresponding to an entry of 1 in the first. Hence, you can pass the output as an argument to the "sum" command,
>> sum(M(M(:,1)==1,2))
ans =
9121
If you want to repeat this for all the values in Var1(i.e. 1,2 and 3) then you can make use of MATLAB for-loop like this:
for i = 1:3
sum1(i,1) = sum(M(M(:,1)==i,2));
end
Refer to the following documentation for logical indexing:
I hope this helps!
Thanks,
Tushar
  댓글 수: 1
Gudmund Hjelmqvist
Gudmund Hjelmqvist 2015년 11월 5일
Thank you! This was what I as looking for!

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

추가 답변 (1개)

Stephen23
Stephen23 2015년 11월 6일
Although there is already an accepted answer to this question, the accepted answer misses the much simpler and neater alternative accumarray, which does not require any loops:
>> M = [1,132;1,8989;2,898;2,9898;2,89898;3,90909;3,90909]
M =
1 132
1 8989
2 898
2 9898
2 89898
3 90909
3 90909
>> S = accumarray(M(:,1),M(:,2))
S =
9121
100694
181818

카테고리

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