I am new to Matlab and I have a matrix:
M =[NaN NaN NaN 2010 5454;
NaN NaN 2009 3000 5000
NaN 2011 3256 5454 6000
2009 4000 5666 6545 5555
5000 5666 6000 7000 8000];
I want to replace values closest to Nan with a value of 2010. I know how to do it manually and one by one. Is there any to create a loop to find these values and replace them? The result should look like this:
M =[NaN NaN NaN 2010 5454;
NaN NaN 2010 3000 5000
NaN 2010 3256 5454 6000
2010 4000 5666 6545 5555
5000 5666 6000 7000 8000];
Thank you in advance.
It is possible without defining any explicit loops. Below are the steps and sample code.
find
function to determine which elements areNaN
.Sample code
Thanks to @crazyGamer for improving the answer with explanations and clearer variable names.
You can use 2D-convolution to detect entries that are close to a
NaN
; select non-NaN
's among those entries, and write the desired value there.Closeness is defined by means of a neighbourhood binary mask. This usually has
4
neighbours (up, down, left, right) or8
(including diagonals).The code is generalized to use either mask as per choice.
Solution