How to Remove NaN Values from a Matrix using MATLAB


In MATLAB, for removing NaN value from a matrix, the following two functions are most widely used.

  • remmissing ()

  • isnan ()

Now let us understand the removal of NaN value from a matrix in MATLAB using these two functions with the help of example programs.

Removing NaN Values Using the isnan () Function

In MATLAB, we can use the "isnan()" function to find the NaN values in a matrix and then can be used to remove them using logical indexing.

The "isnan ()" function returns a value TRUE (logic 1) for NaN elements and FALSE (logic 0) for non-NaN elements.

Syntax of isnan ()

The "isnan ()" function in MATLAB takes the following syntax −

isnan (A)

Where, "A" is the matrix of elements. The "isnan ()" function accepts a parameter and returns a matrix of logical values.

Example 1

For better understanding of the "isnan ()" function in MATLAB, let's consider the following example −

% MATLAB program to remove NaN values using isnan() function

% Creating a matrix with NaN values
X = [1, NaN, 2, 3, 4, NaN, NaN, 5, 6];

% Calling isnan() function to find the indices of the NaN values
Y = isnan(X)

% using logical indexing to getting a new matrix without NaN values
Z = X (~Y)

Output

On execution, it will produce the following output

Y =

  0  1  0  0  0  1  1  0  0

Z =

   1   2   3   4   5   6

Explanation

In this MATLAB program, the "isnan ()" function is used to create a logical matrix "Y" whose dimensions are the same as the original matrix "X". In the matrix "Y", each element is TRUE (logic 1) if the corresponding element in the matrix "X" is NaN, otherwise it is FALSE (logic 0).

The logical indexing X(~Y) returns a matrix Z that contains all the non-NaN elements of the matrix X.

Removing NaN Values Using the remmissing () Function

There is another function "remmissing" in MATLAB that can be used to remove NaN values from a matrix. This function was first introduced in MATLAB R2016b version. The best part of this function is that it provides a more easy way to remove NaN values from a matrix in MATLAB.

Syntax

The remmissing () function takes the following syntax −

X=[1,NaN,2]
Y=remmissing(X)

Example 2

Consider the following example to understand the working of the remmissing function.

% MATLAB program to remove NaN values using remmissing function

% Creating a matrix in NaN values
X = [1, NaN, 2, 3, 4, NaN, NaN, 5, 6];

% Calling remmissing() over the matrix A to remove NaN values
Y = remmissing(X)

Output

It will produce the following output

Y = 1  2  3  4  5  6

Conclusion

This is all about how you can remove NaN values from a matrix using MATLAB.

Updated on: 26-Jul-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements