How to find a nonzero number between two zeros in a cell array in matlab

I have an array of cells (11000x500)with three different types of elements. 1) Nonzero paired 2) zero 3) Empty cell

I would like to find all cases of a nonzero number between two zeros.

eg. A = {123 13232 132 0 56 0 12 0 0 [] [] []};

I need the following output out = logical([0 0 0 0 1 0 1 0 0 0 0 0]);

I used cellfunand isequallike this

out = cellfun(@(c)(~isequal(c,0)), A);

and got the following conclusion

out = logical([1 1 1 0 1 0 1 0 0 1 1 1]);

I need help with the next step, where I can ignore the serial 1'sand only accept "1" between two0's

Can someone help me with this?

Thank!

+4
source share
3 answers

conv 0 ( , ~ isequal):

out = cellfun(@(c)(isequal(c,0)), A);      % find 0 elements
out = double(out);                         % cast to double for conv
% elements that have more than one 0 neighbor
between0 = conv(out, [1 -1 1], 'same') > 1;

between0 =

   0   0   0   0   1   0   1   0   0   0   0   0

( , , @TasosPapastylianou, True.)

, . , find:

between0 = find(conv(out, [1 -1 1], 'same') > 1);   

between0 =

   5   7
+2

( ) out:

out = logical([1 1 1 0 1 0 1 0 0 1 1 1]);
d = diff([out(1) out]); % find all switches between 1 to 0 or 0 to 1
len = 1:length(out); % make a list of all indices in 'out'
idx = [len(d~=0)-1 length(out)]; % the index of the end each group
counts = [idx(1) diff(idx)]; % the number of elements in the group
elements = out(idx); % the type of element (0 or 1)
singles = idx(counts==1 & elements==1)

:

singles =

   5   7

:

out = false(size(out)); % create an output vector
out(singles) = true % fill with '1' by singles

:

out =

   0   0   0   0   1   0   1   0   0   0   0   0
+3

Another solution, this completely eliminates your original logical matrix, but I don't think you need it.

A = {123 13232 132 0 56 0 12 0 0 [] [] []};
N = length(A);

B = A;                                 % helper array
for I = 1 : N
   if isempty (B{I}), B{I} = nan; end; % convert empty cells to nans
end                                            
B = [nan, B{:}, nan];                  % pad, and collect into array

C = zeros (1, N);                      % preallocate your answer array
for I = 1 : N; 
  if ~any (isnan (B(I:I+2))) && isequal (logical (B(I:I+2)), logical ([0,1,0]))
    C(I) = 1; 
  end
end
C = logical(C)

C =
     0  0  0  0  1  0  1  0  0  0  0  0
+1
source

Source: https://habr.com/ru/post/1653702/


All Articles