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

1 回表示 (過去 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 Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by