MATLAB: Replace NaN with previous values

arraynanreplacereplacingvector

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 (118×17) 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,

Best Answer

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