Filter löschen
Filter löschen

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 Ansichten (letzte 30 Tage)
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,];

Antworten (2)

Image Analyst
Image Analyst am 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 am 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

Kategorien

Mehr zu Operating on Diagonal Matrices finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by