Clear Filters
Clear Filters

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

1 view (last 30 days)
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

Accepted Answer

Ameer Hamza
Ameer Hamza on 5 Dec 2020
Edited: Ameer Hamza on 5 Dec 2020
Try this
str = '00000001111000000000111111100000000000000011111111';
x = diff([0 find(diff(str-'0')) numel(str)])
Result
>> x
x =
7 4 9 7 15 8

More Answers (1)

Image Analyst
Image Analyst on 5 Dec 2020
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.

Categories

Find more on Line Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!