How to create a loop to sum across columns conditional on index matching?
2 次查看(过去 30 天)
显示 更早的评论
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.
2 个评论
Matt J
2016-10-25
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).
You mean you want
sum A(i,1:A(i,1))
for each i?
采纳的回答
Chris Dischner
2016-10-25
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
2 个评论
Matt J
2016-10-27
编辑:Matt J
2016-10-27
I get the summation vector for each i with some values >1, which should not be the case since it's strictly binary and cannot exceed 1 in any column sum, for any i
The chances are excellent that it is the input data's fault and not the code's, i.e, that you have not successfully fulfilled the condition "cannot exceed 1 in any column sum, for any i". There is no reason this should be the case just because A(:,2:end) are all zeros and ones.
更多回答(2 个)
Teja Muppirala
2016-10-28
result = [unique(A(:,1)) grpstats(A(:,2:end),A(:,1),@any)] % Keep it binary
or
result = [unique(A(:,1)) grpstats(A(:,2:end),A(:,1),@sum)] % Take the sum
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!