MATLAB: How to create a loop to sum across columns conditional on index matching

loopsum

Hello, I have a binary matrix, with a corresponding index in the first column. For example:
A = [1 1 0 1 0 0 1 ..0]
1 0 0 0 1 1 0 ..1
2 ...
2 ...
2 ...
3 ...
[... ... ]
I want to sum all binary elements corresponding to 1 in the index, 2 in the index, etc. (i.e. index is =1 in the first and second row,so sum across each column, and so on). For the index, the number of corresponding rows with same index number varies across the dataset. I would appreciate all help and advice on how to do this.

Best Answer

What about something like this?
Assuming your index values are sequential:
aMax = max(A(:,1));
for i = 1:aMax
aSum(i,:) = sum(A(A(:,1) == i,:));
end
Will get you the sums. You can use modular arithmetic to get you to the bit representation
(eg, 1+1+1 = 3 ==> 3 mod 2 = 1