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

조회 수: 2 (최근 30일)
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!

채택된 답변

Andrei Bobrov
Andrei Bobrov 2016년 10월 18일
편집: Andrei Bobrov 2016년 10월 18일
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;

추가 답변 (4개)

KSSV
KSSV 2016년 10월 18일
편집: KSSV 2016년 10월 18일
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 2016년 10월 18일
편집: Gareth Lee 2016년 10월 18일
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
Jan
Jan 2016년 10월 18일
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.

댓글을 달려면 로그인하십시오.


Walter Roberson
Walter Roberson 2016년 10월 18일
편집: Walter Roberson 2016년 10월 18일

Jan
Jan 2016년 10월 18일
[B, N] = RunLength(Data(:, 2));
B(B == 0 & N >= 3) = NaN;
Data(:, 2) = reshape(RunLength(B, N), [], 1);

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by