MATLAB: Summing specific values in arrays

matricies arrays summing tables statistics

If i have something for example say
2,3
4,5
2,5
1,5
2,1
1,1
how would i sum up all the values on the second column for values of the first column. For example for all the numbers in the first column that have a value 2, I want to some up all the values the second column corresponding to 2. i.e
2,3
2,5
2,1
would be the only things considered and the answer would be (3+5+1) which is 9. These are all the values to the right of 2. I hope this makes sense, and any help would be appreciated.

Best Answer

If you don't need all values you can use the one-liner
s = sum(X(X(:,1)==2, 2));
X(:,1)==2 results in a logical array that has 1's at all the rows that are equal to 2, else zero. If you use this as an index to X(.,2), the values in the 2nd column are selected for those rows in column 1 that equal 2. These values are summed, and you got your desired result.