Replace NaN with previous values
19 次查看(过去 30 天)
显示 更早的评论
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,
0 个评论
采纳的回答
Chad Greene
2015-1-5
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 个评论
Chad Greene
2015-1-5
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
2015-1-5
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!