MATLAB: How to remove NaN values from a matrix and retain matrix shape

MATLABnan

Say for example I have the following array
X = [1 3 4; 5 6 8; NaN NaN NaN]
X =
1 3 4
5 6 8
NaN NaN NaN
I want to get rid of all the NaN values so I use
X(~isnan(X))
ans =
1
5
3
6
4
8
Now the array has changed from a 3×3 to a 1×6. I want to be able to retain the matrix layout and only remove the NaN values giving a 2×3
X =
1 3 4
5 6 8
Thanks

Best Answer

X(all(isnan(X),2),:)=[]
Related Question