Replace rows with NaN only if there are more than two continous zero values in the same column

1 view (last 30 days)
I am a begginer in Matlab. I need to replace with NaN all rows which contain more than two continous zero values in the same column (second column). Look at the next example:
Input=
124.2 0 7.2 -4.8
131.1 1.8 1.4 -1.2
131.9 0 1 3
123 0 4 5
987 0 0 9
2323 3 3 3
2323 0 3 2
3 0 6 0
221 3.1 4 5.6
57 1 231 122
987 0 2 7
4454 0 3 4
3 0 0 2
434 0 2 0
Output=
124.2 0 7.2 -4.8
131.1 1.8 1.4 -1.2
131.9 NaN 1 3
123 NaN 4 5
987 NaN 0 9
2323 3 3 3
2323 0 3 2
3 0 6 0
221 3.1 4 5.6
57 1 231 122
987 NaN 2 7
4454 NaN 3 4
3 NaN 0 2
434 NaN 2 0
Thanks for your help fellows!

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 18 Oct 2016
Edited: Andrei Bobrov on 18 Oct 2016
t = Input(:,2) == 0;
[ii,c] = bwlabel(t);
x = accumarray(ii+1,1);
x = x(2:end);
z = 1:c;
Input(ismember(ii,z(x > 2)),2) = nan;
for all Input
t = Input == 0;
z = cumsum(diff([zeros(1,size(Input,2));t]) == 1);
ii = bsxfun(@plus,z,cumsum([0,z(end,1:end-1)])).*t;
b = accumarray(ii(:)+1,1);
Output = Input;
Output(ismember(ii,find(b(2:end)>2 ))) = nan;

More Answers (4)

KSSV
KSSV on 18 Oct 2016
Edited: KSSV on 18 Oct 2016
A = [124.2 0 7.2 -4.8
131.1 1.8 1.4 -1.2
131.9 0 1 3
123 0 4 5
987 0 0 9
2323 3 3 3
2323 0 3 2
3 0 6 0
221 3.1 4 5.6
57 1 231 122
987 0 2 7
4454 0 3 4
3 0 0 2
434 0 2 0];
c2 = A(:,2) ; % pick second column
temp = diff(c2 == 0 ) ;
bs = find( temp == 1 ) + 1 ; % start of zero
be = find( temp == -1 ) ; % end of zero
be = [be(2:end) ; length(c2)] ;
%%replace with Nan's
for i = 1:length(bs)
c2(bs(i):be(i)) = NaN ;
end
A(:,2) = c2 ;

Gareth Lee
Gareth Lee on 18 Oct 2016
Edited: Gareth Lee on 18 Oct 2016
First, you can find the column with continous zeros(more than two), then find the index for replacement with nan. for example:
a =(A==0);
a = double(a); % you can loop to find the number of 1 (more than 2)
m = a(:,2);
[cc,dd] = regexp(sprintf('%d', m), '1{3,}', 'start', 'end'); % find the index of continous ones
Next, replace the zeros between cc and dd with nan.
  1 Comment
Jan
Jan on 18 Oct 2016
The conversion between DOUBLEs and CHARs is time consuming and prone to errors and rounding for floating point values. Better stay at the same type.

Sign in to comment.


Walter Roberson
Walter Roberson on 18 Oct 2016
Edited: Walter Roberson on 18 Oct 2016

Jan
Jan on 18 Oct 2016
[B, N] = RunLength(Data(:, 2));
B(B == 0 & N >= 3) = NaN;
Data(:, 2) = reshape(RunLength(B, N), [], 1);

Products

Community Treasure Hunt

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

Start Hunting!