But the above codes doesn't remove NAN
One important property of NaN is that NaN is never equal to anything, including NaN. Hence NaN == NaN is always false, and NaN ~= NaN is always true.So, yes your code can't work.
As others have said, you have to use isNaN to check if a number is NaN. As usual in matlab, isNaN works on matrices too, so there's no point in using a loop:
It's unclear what the purpose of the k loop is in a code.
Finally, if you are hell-bent on using a loop, you should never hard code the end of a loop when you're looping over the elements of a matrix/vector. Always ask matlab how many elements there are. That way if the number of elements in the matrix/vector changes, you don't have to edit your code: