0
votes

I have a cell matrix containing numeric values and NaN. How can I remove the NaN values and "trim" my matrix.

For example I have the following matrix:

A = { 1, 12, NaN; 1 ,4, NaN; 1 , 2 , NaN ; NaN, NaN, NaN; 1, 2, NaN };

I would like to remove the NaN and resize the matrix to have this matrix. Can it be done without loop ? (using vectorisation)

A = [ 1, 12; 1, 4; 1, 2; 1, 2];
2
I remain with my previous statement (see my answer below): Since there is no clue, that a NaN can't be in the first or second column, it is impossible - from my point of view - to maintain a certain shape of the resulting matrix automatically. If there is prior knowledge, like NaNs can only occur in the third column or whole rows are NaNs, please let us know, so there might be further options. As for now, any resizing must be done manually. - HansHirse

2 Answers

2
votes
A = { 1, 12, NaN; 1 ,4, NaN; 1 , 2 , NaN ; NaN, NaN, NaN; 1, 2, NaN };
A = cell2mat(A) ;   % convert the given cell to matrix         
[m,n] = size(A) ;   % get size of the matrix 
A(sum(isnan(A),2)==n,:) = [] ;  % remove rows with all NaN's in a row 
[m,n] = size(A) ;   % get updated size of A 
A(:,sum(isnan(A),1)==m) = [] ;  % remove columns with all NaN's in a column 

Result

 A = [1    12
      1     4
      1     2
      1     2]
0
votes

At first glance, I don't see a way to (automatically) preserve the "shape" (dimensions) of the matrix. For the conversion and extraction, there is a simple solution:

B = cell2mat(A)
B =

     1    12   NaN
     1     4   NaN
     1     2   NaN
   NaN   NaN   NaN
     1     2   NaN

B = B(~isnan(B))
B =

    1
    1
    1
    1
   12
    4
    2
    2

I will further think about the (automatic) resizing.