MATLAB: SUM of selected elements in Matrix

sumuser define

i have matrix
M = [1 1 2 60;
2 3 2 90;
3 1 3 240;
4 2 3 200;
5 3 3 160]
i want to select 1 from 2nd column and acoording to that i want to SUM of 60 and 240. same way i want to select 3 from 2nd column and SUM of 90 and 160.
how to creat?

Best Answer

Are you looking for something like this
M = [1 1 2 60;
2 3 2 90;
3 1 3 240;
4 2 3 200;
5 3 3 160];
result = splitapply(@sum, M(:,4), M(:,2))
Result
>> result
result =
300
200
250