Replace NaN with previous values

11 views (last 30 days)
Luka
Luka on 5 Jan 2015
Commented: Chad Greene on 5 Jan 2015
Hello. I have the following issue and i've spent an entire working on it and i never was able to solve it. Now lets say suppose we have a array such as
A =
NaN 5 6 7 8
32 NaN NaN 21 NaN
NaN 0 12 NaN 6
34 NaN NaN NaN NaN
1 24 52 52 44
NaN 0 2 4 1
NaN NaN 3 1 4
^The above is just an example, the data array which i got is large (118x17) to be precise and it has NaN's filled everywhere (like the example of 'A')
Okay so i basically want to copy the value below 'NaN' and replace that value for NaN. And where NaN is at the bottom on the column, i need to copy the above value and replace it with 'NaN'. In short the end result should look like this
A =
32 5 6 7 8
32 0 12 21 6
34 0 12 52 6
34 24 52 52 44
1 24 52 52 44
1 0 2 4 1
1 0 3 1 4
the code also should be able to work with any kind of array given, not only the example given.
Please please suggest some code, im desperate here.
Thanks in advance,

Accepted Answer

Chad Greene
Chad Greene on 5 Jan 2015
Use repnan on each column:
A = [NaN 5 6 7 8;
32 NaN NaN 21 NaN;
NaN 0 12 NaN 6;
34 NaN NaN NaN NaN;
1 24 52 52 44;
NaN 0 2 4 1;
NaN NaN 3 1 4;]
for k = 1:size(A,2)
A(:,k) = repnan(A(:,k),'next');
A(:,k) = repnan(A(:,k),'previous');
end
A =
32 5 6 7 8
32 0 12 21 6
34 0 12 52 6
34 24 52 52 44
1 24 52 52 44
1 0 2 4 1
1 0 3 1 4
  2 Comments
Chad Greene
Chad Greene on 5 Jan 2015
The first call replaces each NaN with the next finite value, and the second call replaces the leftover NaNs with the previous finite value.
Chad Greene
Chad Greene on 5 Jan 2015
You want loops? We got 'em.
for k = 1:size(A,2) % k moves left to right
LastReal = NaN;
for n = size(A,1):-1:1 % n moves bottom to top
if isfinite(A(n,k))
LastReal = A(n,k);
else
A(n,k) = LastReal;
end
end
LastReal = NaN;
for m =1:size(A,1)% m moves top to bottom
if isfinite(A(m,k))
LastReal = A(m,k);
else
A(m,k) = LastReal;
end
end
end
It's not the most efficient, but for 118x17 it should be fine.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!