How to return the sequential number of nonzero and zero elements in a list?
Show older comments
Given list A = [1, 2, 3, 4, 5, 0, 0, 3, 4, 5, 0, 0, 0, 0], how can I return a matrix of the sequential number of non-zero and zero elements in the list? In the above example, the output should be B = [5, 2; 3, 4].
1 Comment
Image Analyst
on 23 Oct 2015
And what would you want for this:
A = [0, 0, 1, 2, 3, 0, 0, 3, 4, 5, 0, 0, 0]
or would you never have a different number of zero and non-zero stretches?
Accepted Answer
More Answers (1)
Image Analyst
on 23 Oct 2015
Sounds a lot like homework. Here's a hint:
A = [1, 2, 3, 4, 5, 0, 0, 3, 4, 5, 0, 0, 0, 0]
% Find lengths of non-zero stretches of data.
labeled = bwlabel(A ~= 0)
measurements = regionprops(labeled, 'Area', 'PixelList');
allAreas1 = [measurements.Area] % Produces 5 3
% Find lengths of zero stretches of data.
labeled = bwlabel(A == 0)
measurements = regionprops(labeled, 'Area', 'PixelList');
allAreas0 = [measurements.Area] % Produces 2 4
% Interleave allAreas1 and allAreas0 to form "B"
% See if you can do this part yourself.
Categories
Find more on Deep Learning Toolbox 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!