Please how to calculate the number of 1 and 0 in each position in a binary vector

조회 수: 2 (최근 30일)
For example my vector is like this: Vector = 00000001111000000000111111100000000000000011111111
I want to calculate the number of 0 in each position and the number of 1 in each position like 7zeros4ones9zeros7ones.....
Please need help

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 12월 5일
편집: Ameer Hamza 2020년 12월 5일
Try this
str = '00000001111000000000111111100000000000000011111111';
x = diff([0 find(diff(str-'0')) numel(str)])
Result
>> x
x =
7 4 9 7 15 8

추가 답변 (1개)

Image Analyst
Image Analyst 2020년 12월 5일
I see you've already accepted an answer so I guess this isn't what you wanted, but it's what I thought you wanted:
vec = [0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1];
% Find the lengths of the stretches of 1's.
props = regionprops(logical(vec), 'Area');
numOnes = [props.Area]
% Find the lengths of the stretches of 0's.
props = regionprops(logical(vec==0), 'Area');
numZeroes = [props.Area]
You'll see the lengths of the runs of both 1's and 0's:
numOnes =
4 7 8
numZeroes =
7 9 15
and it gives the number of 1's and 0's to you explicitly without having to know whether the first element is a 0 or 1 if they're interlaced like Ameer's answer.

카테고리

Help CenterFile Exchange에서 Surface and Mesh Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by