Replace NaN with previous values
19 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Luka
am 5 Jan. 2015
Kommentiert: Chad Greene
am 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,
0 Kommentare
Akzeptierte Antwort
Chad Greene
am 5 Jan. 2015
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 Kommentare
Chad Greene
am 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
am 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!