Count sequence of zeros with For loop
Show older comments
Let's say I have the following matrix:
a= 3 0 7 8 0 0 1 5
1 0 5 0 0 2 3 0
0 2 0 0 1 4 7 0
2 0 5 9 0 0 0 0
3 0 1 0 0 0 1 5
I wish to count the number of continuous 0s every time a 0 exists in each column. So for the above example, I want my output to be
zeros= 1 2 1 2 2 1 1 3
2 1 2 2
Is it possible to do this using a For loop? The output for each column can be made into a separate file if necessary.
Thank you!
Answers (3)
Roman Müller-Hainbach
on 29 Aug 2017
It is not pretty, but it does what you want:
function zeros = contzeros(A)
zeros = cell( 1, size(A,2) );
for colind = 1:length(zeros)
column = A(:,colind)';
if column(1) == 0
zeros{colind} = max([0,find(column~=0,1)])-1;
end
[~,remains] = strtok(column,0);
while ~isempty(remains)
n = max([0,find(remains~=0,1)])-1;
if n == -1 && remains(end) == 0
zeros{colind}(end+1,1) = length(remains);
elseif n >= 1
zeros{colind}(end+1,1) = n;
end
[~,remains] = strtok(remains,0); %#ok<STTOK>
end
end
end
Notice that the output is a cell-array.
Simply use diff and then run over the columns:
a = [...
3 0 7 8 0 0 1 5
1 0 5 0 0 2 3 0
0 2 0 0 1 4 7 0
2 0 5 9 0 0 0 0
3 0 1 0 0 0 1 5
];
idx = a([1,1:end,end],:)==0;
idx([1,end],:) = false;
tmp = num2cell(diff(idx,1,1),1);
fun = @(v)find(v<0)-find(v>0);
out = cellfun(fun,tmp,'uni',0);
giving the output in a cell array:
>> out{:}
ans = 1
ans =
2
2
ans = 1
ans =
2
1
ans =
2
2
ans =
1
2
ans = 1
ans = 3
a = [3 0 7 8 0 0 1 5; ...
1 0 5 0 0 2 3 0; ...
0 2 0 0 1 4 7 0 ; ...
2 0 5 9 0 0 0 0 ; ...
3 0 1 0 0 0 1 5];
nCol = size(a, 2);
List = cell(1, nCol);
for iCol = 1:nCol
[B, N] = RunLength(a(:, iCol));
List{iCol} = N(B == 0);
end
You can create a cheap version of RunLength also:
function [b, n] = cheapRunLength(x)
d = [true; diff(x) ~= 0]; % TRUE if values change
b = x(d); % Elements without repetitions
k = find([d', true]); % Indices of changes
n = diff(k); % Number of repetitions
end
With the C-Mex this needs 40-50% of the runtime, but for small data, this might be not important.
Categories
Find more on Logical 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!