Replace NaN in a matrix

3

I have this information

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 you replace only the NaN with the average value of the values on your 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 it is important the location of the NaNs and their respective adjacent values, for example for the NaN (2,3), it has to be replaced by 7 and 9

    
asked by AnesG 06.10.2016 в 22:12
source

1 answer

1

A coarse , but functional, way would be something like this:

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;
[idx,jdx] = find(isnan(Mat));
for k=1:length(idx)
    try
        Mat(idx(k),jdx(k)) = mean([Mat(idx(k),jdx(k)-1),Mat(idx(k),jdx(k)+1)]);
    catch err
        continue;
    end
end

Where the idea is: first use the function find to get all the positions of the NaN . After iterating about the (i,j) indexes that were obtained, and trying to make the corresponding substitution, it is likely that in some cases the indexes are outside the limits of the matrix and therefore try-catch is used for when that happens. execution does not stop, continue with another element and in the current one no change is made.

    
answered by 07.10.2016 / 02:38
source