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!
0 个评论
采纳的回答
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;
0 个评论
更多回答(4 个)
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 ;
0 个评论
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
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
2016-10-18
编辑:Walter Roberson
2016-10-18
Odd how two different people have such similar tasks for the same data...
0 个评论
Jan
2016-10-18
[B, N] = RunLength(Data(:, 2));
B(B == 0 & N >= 3) = NaN;
Data(:, 2) = reshape(RunLength(B, N), [], 1);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!