Arthur Tarasov
Arthur Tarasov

Reputation: 3791

How to remove rows that contain NaNs in a specific column from a table in Matlab?

I have a table, which is similar to this one:

Rows = {'Row1';'Row2';'Row3'};
Column1 = [NaN;1;2];
Column2 = [4;5;NaN];
Column3 = [NaN;NaN;4];
Table1 = table(Column1,Column2,Column3,...
'RowNames',Rows)

Table1 = 

        Column1    Column2    Column3
        _______    _______    _______

Row1    NaN          4        NaN    
Row2      1          5        NaN    
Row3      2        NaN          4    

I need to remove rows that have NaN in Column1. All other rows, which may or may not have NaNs in other columns, should stay. So the desired output should look like this:

Table2 = 

        Column1    Column2    Column3
        _______    _______    _______

Row2      1          5        NaN    
Row3      2        NaN          4    

Of course, this is just a simplified example. The real table is huge and I will be working with one column at a time, which is why I need to selectively remove rows that contain NaN in a specific column.

Is there a way to do it without converting the table into a struct array or something else?

Upvotes: 1

Views: 1445

Answers (1)

akamath
akamath

Reputation: 570

I tried this:

Table2 = Table1(~isnan(Table1.Column1), :)

I make use of the fact that the first column is called Column1.

Note that Table1.Column1 returns:

ans =

   NaN
     1
     2

and so choosing the non-NaN values in this column is achieved by using ~isnan().

The rest is purely indexing into the table. I get the following with the command above:

Table2 = 

        Column1    Column2    Column3
        _______    _______    _______

Row2    1            5        NaN    
Row3    2          NaN          4   

Upvotes: 4

Related Questions