Search code examples
excelmatlabcell-array

How to delete entire row which has empty cell in any column, of a excel sheet containing both texts and numbers


This is my data in excel. How to delete entire row having any empty cell in any column in MATLAB. The sheet contains both texts and numbers,

(col1  col2 col3) 
OAS01   0   74
OAS02   0   55
OAS03   0.5 73
OAS04       24
OAS05       21
OAS06       20
OAS07   0   74
OAS08   0   52
OAS09   1   30
OAS01       81

I want to get output like this by deleting of entire and all rows which have any empty cell

(col1 col2 col3) 
OAS01 0 74 
OAS02 0 55
OAS03 0.5 73 
OAS07 0 74 
OAS08 0 52 
OAS09 1 30 

I have tryied but not working well

[num, text, a] = xlsread('data.xlsx');

for i = 1:size(data,1)

if isnan(num(i,1))

    a(i,:) =[];

    num(i,:) =[];

else 
   a(i,:) =a(i,:);   
   num(i,:) =num(i,:);   
end

end

xlswrite('newfile.xlsx', a);

Solution

  • Much more elegant way:

    T = {'a','b';'','c';'d','e'}
    
    >> T = 
    
    'a'    'b'
    ''     'c'
    'd'    'e'
    
     T(any(cellfun(@isempty,T),2),:) = []
    
    >> T =
    
    'a'    'b'
    'd'    'e'
    

    ------EDIT-----

    OP said it is not working, so I checked, and it is because empty cells gets loaded as NaNs by the xlsread function, so this line should fix it:

     [num, text, a] = xlsread('data.xlsx');
     a(any(cellfun(@(x) any(isnan(x)),a),2),:) = [];
    

    where a is the 3 by 3 cell that the OP loaded in.

    Explanations: cellfun is largely used and well documented, in this particular case, we are interested in setting rows with NaN to [], so we are using matlab's isnan to detect cells which contains NaN, we then wrap the any function outside, which returns a boolean 1 if there is a NaN or a 0 if there isn't a NaN. The outer any generates the boolean index of which (0 is a row with no NaNs and 1 is a row with NaNs) we filter the data on.