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

1 次查看(过去 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 中查找有关 Line Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by