user1157844
user1157844

Reputation: 41

Removing NaN elements from a matrix

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]

Upvotes: 4

Views: 6639

Answers (3)

Pursuit
Pursuit

Reputation: 12345

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.

Upvotes: 2

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

Here it is - please note that the code is not robust. It assumes that indeed in every row there is a NaN element.

While it is not a vectorized solution, it has other advantages - like a clear code.

for i=1:size(A,1)
   x = A(i,:);
   x(isnan(x)) = [];
   B(i,:) = x;
end

B

B =

1     2
3     4
5     6

Upvotes: 0

ifnull
ifnull

Reputation: 249

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))'

Upvotes: 6

Related Questions