Search code examples
matlabcell

Remove NaN from cell matrix in MATLAB


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];

Solution

  • 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]