Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing NaN elements from a matrix

Tags:

matlab

There is one NaN element per row, I want to remove it.

A=[NaN  1  2;  
    3  NaN 4;  
   NaN  5  6];  

The desired output is:

[1 2;  
 3 4;  
 5 6]
like image 676
user1157844 Avatar asked Feb 22 '23 19:02

user1157844


2 Answers

A = [NaN 1 2 ; 3 NaN 4; NaN 5 6]
sz = size(A);
B = reshape(A', size(A,1)*size(A,2), 1);
B(isnan(B)) = [];
B = reshape(B, sz(2)-1, sz(1))'
like image 142
ifnull Avatar answered Mar 02 '23 22:03

ifnull


I thought it could be done in one line, but I was wrong. See solution below:

Given (added row helps me debug my indexing below):

>> A = [NaN 1 2 ; 3 NaN 4; NaN 5 6; 7 8 NaN]
A =
   NaN     1     2
     3   NaN     4
   NaN     5     6
     7     8   NaN

Then:

>> Atrans = A';
>> B = reshape(    Atrans(~isnan(Atrans))    ,[],size(Atrans,2))'
B =
     1     2
     3     4
     5     6
     7     8

Incidentally, the Matlab idiom of performing a simple logical check on an array within an logical indexing operation is very common and incredibly useful. The archetypical example is:

>> x(x>0)   %This returns a 1D column vector of all values of x 
            %which are greater than 0, regardless of the initial
            %size of x.  Multidimensional inputs are unwrapped 
            %column-first

Everything else above is size and dimension handling.

like image 29
Pursuit Avatar answered Mar 02 '23 22:03

Pursuit