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

1 次查看(过去 30 天)
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,];

回答(2 个)

Image Analyst
Image Analyst 2023-7-1
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 2023-7-1
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

产品

Community Treasure Hunt

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

Start Hunting!

Translated by