Summing groups of ones

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

Oleg Komarov
Oleg Komarov 2012년 4월 24일
Can you provide an example of input and output?
William
William 2012년 4월 24일
This might be helpful: http://www.mathworks.com/matlabcentral/newsreader/view_thread/160813

댓글을 달려면 로그인하십시오.

 채택된 답변

Image Analyst
Image Analyst 2012년 4월 24일

0 개 추천

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

Sonia Wiemann
Sonia Wiemann 2012년 4월 24일
This solution is just giving me one number in answer.....I have a data set that is 000001111110000001111100000011111 with much longer sections....can I get the program to feed back an answer like 5,6,6,5,6,5....counting each group separately?
Andrei Bobrov
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
Image Analyst
Image Analyst 2012년 4월 25일
Sonia: See that answer in your post about that question.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Rick Rosson
Rick Rosson 2012년 4월 24일

1 개 추천

y = cumsum(x);
d = x(2:end) - x(1:end-1);
k = ( d == -1 );
z = y(k);
Andrei Bobrov
Andrei Bobrov 2012년 4월 24일

0 개 추천

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)]

카테고리

도움말 센터File Exchange에서 Surrogate Optimization에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by