Clear Filters
Clear Filters

How to count number of only those zeros which are lying between 2 one's in a very simplified way in the given matrix?

3 views (last 30 days)
a = [0, 0, 0, 0, 1, 1, 1, 1, 0, 0 ,0 ,0 ,0 ,0 ,0 ,1 ,1, 1, 1 ,0 ,0 ,0 ,1 ,0 ,0 ,1 ,1 ,1 ,1 ,1 ,0, 0, 1, 1, 1, 1, 1, 0, 0,];

Answers (2)

Image Analyst
Image Analyst on 1 Jul 2023
Here is one way:
a = [0, 0, 0, 0, 1, 1, 1, 1, 0, 0 ,0 ,0 ,0 ,0 ,0 ,1 ,1, 1, 1 ,0 ,0 ,0 ,1 ,0 ,0 ,1 ,1 ,1 ,1 ,1 ,0, 0, 1, 1, 1, 1, 1, 0, 0,];
% Set leading 0's to 1 since they are not between 1's
index = find(a, 1, 'first');
a(1:index) = 1;
% Set trailing 0's to 1 since they are not between 1's
index = find(a, 1, 'last');
a(index : end) = 1;
% All the rest of the 0's are between 1's so
% count them with nnz
numZeros = nnz(a == 0)
numZeros = 14
Is that what you mean?

DGM
DGM on 1 Jul 2023
This uses image processing tools. This is probably more expensive, but it's another idea.
a = [0, 0, 0, 0, 1, 1, 1, 1, 0, 0 ,0 ,0 ,0 ,0 ,0 ,1 ,1, 1, 1 ,0 ,0 ,0 ,1 ,0 ,0 ,1 ,1 ,1 ,1 ,1 ,0, 0, 1, 1, 1, 1, 1, 0, 0];
% invert and pad the array so that we're selecting zeros
% and the interior zero blocks are not on the array edge
b = padarray(~a,[1 0],0,'both');
% get rid of blocks that are on the array edge
b = imclearborder(b);
% count the remaining zeros
numzeros = nnz(b(2,:))
numzeros = 14

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!