Removing NaN from matrix

조회 수: 515 (최근 30일)
Christian
Christian 2017년 4월 19일
댓글: Ashishkumar Gupta 2023년 1월 5일
Hello everybody,
I have a 61x9 double matrix. The columns look like this:
Column 1: 0 1 2 3 4 5 6 7 ... NaN NaN NaN
Column 2: 0 2 3 4 5 6 7 8 4 5 6 3 NaN NaN
Column 3: 0 5 6 6 3 3 6 7 8 5 3 3 6 7 8 5 . . .
That means, every column has a certain amount of values and is filled up with NaNs to get a rectangular double matrix all in all.
Now I want to remove all the NaNs. And I am not quite sure if this is possible, because after removing the NaNs, the size of each column would differ.
For now I have tried something like this:
A(find(isnan(A)))=[]
This code removes the NaNs, but the result is a 1x445 double, where all columns are just add consecutively.
I hope you guys can help me!
Cheers
Christian
  댓글 수: 2
Ganesh Hegade
Ganesh Hegade 2017년 4월 19일
Its better you should replace the NaN with some values.
A(isnan(A)) = -1;
Pampa Dey
Pampa Dey 2021년 8월 25일
how to remove nans from a column?
I have multiple .txt files in which some of them have completely nan values within my interested column how can we remove them in matlab?
could anyone please help?

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

채택된 답변

Jan
Jan 2017년 4월 19일
Exactly: This cannot work, because all columns of a matrix must have the same number of rows. You cannot remove all NaNs and keep the shape of the matrix. You have to decide, what you want instead:
X = X(~any(isnan(X, 2)))
X = X(~all(isnan(X, 2)))
X = X(~isnan(X))
Or perhaps you want a cell array containing the different columns vectors?
  댓글 수: 2
Christian
Christian 2017년 4월 19일
Ok, that's what I thought. So I will continue using cells instead.
Ashishkumar Gupta
Ashishkumar Gupta 2023년 1월 5일
did not work for a .struct!!!
Any other way out to remove NaNs from a struct having 50-60 variables

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

추가 답변 (1개)

Biswajit Ojha
Biswajit Ojha 2019년 4월 30일
"X = X(~any(isnan(X, 2)))
X = X(~all(isnan(X, 2)))
X = X(~isnan(X)) "
dear Jan,
can you please explain why you have used those '2' s in the command?
  댓글 수: 1
Yuanhanqing Huang
Yuanhanqing Huang 2019년 7월 25일
I think there are some little errors. Maybe the right code should be:
X = X(~all(isnan(X), 2))
It means that we find the rows the elements of which are all nan. '2' denotes the results are in column. That being said, the any operation is implemented regarding each row.

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

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by