4

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]
Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
user1157844
  • 41
  • 1
  • 2

3 Answers3

6
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))'
ifnull
  • 239
  • 2
  • 6
2

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.

Pursuit
  • 12,285
  • 1
  • 25
  • 41
0

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
Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
  • 1
    Are you sure, your code does, what the question was asking for? `A(isnan(A))=[]` returns column-wise array of `A`. When applying `reshape` (note the syntax error with `sz(A,.)`) it finally swaps the first elements of the first and second row. – Torbjörn Jan 19 '12 at 07:15