Search code examples
stringmatlabcellnanempty-list

Removing 'NaN' strings and [] cells from cell array in Matlab


I have a cell array, given as

raw = {100 3.2 38 1;
       100 3.7 38 1;
       100 'NaN' 'NaN' 1;
       100 3.8 38 [];
       'NaN' 'NaN' 'NaN' 'NaN';
       'NaN' 'NaN' 'NaN' []; 
        100 3.8 38 1};

How can I remove the rows which have at least one 'NaN' string and empty cell []? Thus, in this case, I want to remove 3rd, 4th, 5th and 6th row from the above-mentioned cell array. Thanks in advance!


Solution

  • In your cellarray the values NaN are defined as string and not as the "special" value NaN

    In this case, you can use the functions isempty and isfloat to identify which elements of the cellarray are either empty or of type float:

    % Remove rows with empty cells
    idx=any(cell2mat(cellfun(@isempty,raw,'UniformOutput',false)),2)
    raw(idx,:)=[]
    
    % Remove rows with 'NaN'
    idx=all(cell2mat(cellfun(@isfloat,raw,'UniformOutput',false)),2)
    raw(~idx,:)=[]
    

    In the first step you look for the empty cells using the function isempty, since the input is a cellarray you have to use cellfun to apply the functino to all the elements of the cell array.

    isempty returns a cellarray of 0 and 1 where 1 identifies an empty cell, so, after having converted it into an array (with the functino cell2mat) you can identify the indices of the roww with an empty cell using the function any.

    IN the second step, with a similar approach, you can identify the rows containing floating values with the function `isfloat.

    The same approach can be used in case the NaN in your cellarray are defined as "values" and not as strings:

    idx=any(cell2mat(cellfun(@isempty,raw,'UniformOutput',false)),2)
    raw(idx,:)=[]
    idx=any(cell2mat(cellfun(@isnan,raw,'UniformOutput',false)),2)
    raw(idx,:)=[]