Replace with the mean if there are at least six continous NaN in the same column

1 view (last 30 days)
Hello fellows. I am looking for help. In the second column of a matrix, if there are at least six continous NaN, I need to replace it by the mean, calculated from the previous and the last numerical data of the NaN interval. Please look at the next example:
Input:
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
123 NaN 4 5
987 NaN 0 9
3 0 6 0
987 NaN 2 7
4454 NaN 3 4
3 NaN 0 2
434 NaN 2 0
123 NaN 4 5
987 NaN 0 9
987 NaN 0 9
124.2 0 7.2 -4.8
Output:
124.2 0 7.2 -4.8
131.1 1.8 1.4 -1.2
131.9 2.4 1 3
123 2.4 4 5
987 2.4 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.5 2 7
4454 0.5 3 4
3 0.5 0 2
434 0.5 2 0
123 0.5 4 5
987 0.5 0 9
3 0 6 0
987 NaN 2 7
4454 NaN 3 4
3 NaN 0 2
434 NaN 2 0
123 NaN 4 5
987 NaN 0 9
987 NaN 0 9
124.2 0 7.2 -4.8
Thanks in advance for your help!

Accepted Answer

KSSV
KSSV on 18 Oct 2016
Let I be your Input matrix.
c2 = I(:,2) ; % pick second column
temp = diff(isnan(c2 )) ;
bs = find( temp == 1 ) + 1 ; % start of NaN
be = find( temp == -1 ) ; % end of NaN
%%replace with mean
for i = 1:length(be)
m = (c2(bs(i)-1)+c2(be(i)+1))/2 ; % get mean
I(bs(i):be(i),2) = m ;
end

More Answers (2)

Walter Roberson
Walter Roberson on 18 Oct 2016
tf = [false, isnan(YourMatrix(:,2)) .', false];
start_of_block = strfind(tf, [false, true(1,6)]);
end_of_block = strfind(tf, [true(1,6), false]) + 4;
Now for each pair start_of_block(K), end_of_block(K), there is a run of at least 6 NaN occupying YourMatrix(start_of_block(K):end_of_block(K),2) .
meanvals = (YourMatrix(start_of_block-1, 2) + YourMatrix(end_of_block+1, 2));
for K = 1 : length(start_of_block)
YourMatrix(start_of_block(K):end_of_block(K), 2) = meanvals(K);
end

Andrei Bobrov
Andrei Bobrov on 18 Oct 2016
Edited: Andrei Bobrov on 18 Oct 2016
t = isnan(A(:,2));
tt = diff(t);
n = mean([A(tt == 1,2),A([false;tt == -1],2)],2);
ii = t.*cumsum([false;tt == 1]);
n(accumarray(ii(t),1) > 6) = nan;
A(t,2) = n(ii(t));
  3 Comments

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!