Summing with respect to values within variable instead of rows, columns, or equal windows

I have a variable with a similar structure to the following but with many more rows:
a=
1 0.3
1 0.1
2 0.7
2 0.6
2 0.3
2 0.9
3 0.5
4 0.8
4 0.1
5 0.1
5 0.9
5 0.4
Say I want sums of column 2 with respect to each scalar (eg. 1, 2...5) so that I would get a new variable like this:
aa=
1 0.4
2 2.5
3 0.5
4 0.9
5 1.4
I have not found how to sum anything but rows and columns, so how should I go about summing based on values within a variable?

 Accepted Answer

a=[
1 0.3
1 0.1
2 0.7
2 0.6
2 0.3
2 0.9
3 0.5
4 0.8
4 0.1
5 0.1
5 0.9
5 0.4]
uv = unique(a(:,1),'stable');
sidx = accumarray(a(:,1),a(:,2));
[uv sidx]
accumarray() to the rescue!

More Answers (1)

v=unique(a(:,1),'stable');
s=zeros(numel(v),1);
for k=1:numel(v)
s(k,1)=sum(a(ismember(a(:,1),v(k)),2));
end
out=[v s]
%or without a loop
v=unique(a(:,1),'stable');
out=[v arrayfun(@(x) sum(a(ismember(a(:,1),x),2)),v)];

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!