I have this data
Mat=[1 2 3 5;6 7 -9999 9;10 11 12 13;14 -9999 16 17;18 19 -9999 -9999]
Mat(Mat<0)=NaN
Mat =
1 2 3 5
6 7 NaN 9
10 11 12 13
14 NaN 16 17
18 19 NaN NaN
How could I replace only the NaNs with the average value of the values to its left and right
Mat =
1 2 3 5
6 7 8 9
10 11 12 13
14 15 16 17
18 19 NaN NaN
What complicates me is that the location of the NaNs and their respective adjacent values is important, for example for the NaN(2,3), it has to be replaced by 7 and 9
A crude but functional way would be something like this:
Where the idea is the following: first use the function
find
to get all the positions of theNaN
. Then iterate over the indices(i,j)
that were obtained, and try to make the corresponding substitution, it is likely that in some case the indices are outside the limits of the array and therefore it is usedtry-catch
for when that happens the execution does not stop, continue with another element and no change is made to the current one.