How do I remove NaN values from a matrix and retain matrix shape?

13 views (last 30 days)
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 3x3 to a 1x6. I want to be able to retain the matrix layout and only remove the NaN values giving a 2x3
X =
1 3 4
5 6 8
Thanks

Accepted Answer

madhan ravi
madhan ravi on 3 Apr 2019
X(all(isnan(X),2),:)=[]
  1 Comment
Manny Kins
Manny Kins on 3 Apr 2019
Thank you for your quick response! This is a very elegant solution that can be applied to much larger matrices!

Sign in to comment.

More Answers (0)

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!