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!