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

조회 수: 55 (최근 30일)
Manny Kins
Manny Kins 2019년 4월 3일
댓글: Les Beckham 2023년 6월 8일
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

채택된 답변

madhan ravi
madhan ravi 2019년 4월 3일
X(all(isnan(X),2),:)=[]
  댓글 수: 1
Manny Kins
Manny Kins 2019년 4월 3일
Thank you for your quick response! This is a very elegant solution that can be applied to much larger matrices!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Monik gupta
Monik gupta 2023년 6월 8일
Is there any way to remove NaN values without changing shape of the matrix? in case matrix is like following:
X = [1 3 4; 5 NaN 8; 3 4 NaN];
Thanks in Advance.
  댓글 수: 1
Les Beckham
Les Beckham 2023년 6월 8일
You really shouldn't ask questions using an answer to someone else's question.
Nevertheless...
You can't remove them, but you can replace them with something other than NaN. Only you can decide what value to use for the replacement in your particular application.
For example, this will replace them with zero:
X = [1 3 4; 5 NaN 8; 3 4 NaN]
X = 3×3
1 3 4 5 NaN 8 3 4 NaN
X(isnan(X)) = 0
X = 3×3
1 3 4 5 0 8 3 4 0

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by