Summing groups of ones
2 次查看(过去 30 天)
显示 更早的评论
If I have a list of ones and zeros....the ones are clustered together in groups....how can I ask the program to sum the ones within their groups?
2 个评论
William
2012-4-24
This might be helpful: http://www.mathworks.com/matlabcentral/newsreader/view_thread/160813
采纳的回答
Image Analyst
2012-4-24
Just call regionprops (if you have the image Processing Toolbox):
numberOfOnesPerGroup = regionprops(yourArray, 'area');
One line and you're done. This will get you the area (number of touching elements) for each group (elements that all touch each other).
3 个评论
Andrei Bobrov
2012-4-25
numberOfOnesPerGroup = regionprops(~~yourArray(:), 'Area','PixelIdxList' )
numberOfZerosPerGroup = regionprops(~yourArray(:), 'Area','PixelIdxList' );
ons = [ones(numel(numberOfOnesPerGroup),1), cat(1,numberOfOnesPerGroup.('Area'))]
out = zeros(numel(numberOfOnesPerGroup)+numel(numberOfZerosPerGroup),2);
if numberOfOnesPerGroup(1).PixelIdxList(1) < numberOfZerosPerGroup(1).PixelIdxList(1)
out(1:2:end,:) = ons;
out(2:2:end,2) = cat(1,numberOfZerosPerGroup.('Area'));
else
out(2:2:end,:) = ons;
out(1:2:end,2) = cat(1,numberOfZerosPerGroup.('Area'));
end
更多回答(2 个)
Andrei Bobrov
2012-4-24
x1 = [~x(1) x(:)' ~x(end)]
groupones = diff([strfind(x1,[0 1]);strfind(x1,[1 0])]);
variant
x1 = x(:);
k = find([true;diff(x1)~=0]);
out = [x1(k) diff([k,[k(2:end);numel(x1)+1]],1,2)]
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!