%% Manage Import of Empty Fields
% Create an import options object for a file containing empty fields. Use the EmptyFieldRule parameter to manage the import of empty fields in your data. First, preview the data, and then set the EmptyFieldRule parameter for a specific variable. Finally, set EmptyFieldRule for all the variables and import the data.
% Create an import options object for a file containing empty fields. Get the first eight rows of the table using the preview function. The default value for  EmptyFieldRule is  'missing'. Therefore, the importing function treats empty fields as missing and replaces them with the FillValue value for that variable. Using VariableOptions for the third variable, preview the data. Here, the preview function imports the empty fields in the third variable as NaNs.

filename = 'DataWithEmptyFields.csv';
opts = detectImportOptions(filename);
opts.VariableOptions(3) % Display the Variable Options for the 3rd Variable
preview(filename,opts)

%
% Set EmptyFieldRule for the second variable in the table. First, select the variable, and then set EmptyFieldRule to 'auto'. Here, the readtable  function imports empty fields of the categorical variable as <undefined>.

opts.SelectedVariableNames = 'Categorical'; 
opts = setvartype(opts,'Categorical','categorical'); 
opts = setvaropts(opts,'Categorical','EmptyFieldRule','auto');
T = readtable(filename,opts)

%
% Next, set the EmptyFieldRule parameter for all the variables in the table. First, update the data types of the variables appropriately. For this example, set the data type of the fifth and seventh variables to logical and string, respectively. Then, set  EmptyFieldRule for all the variables to 'auto'. The importing function imports the empty fields based on data type of the variable. Here, the  readtable function imports empty fields of the logical variable as 0 and empty fields of the categorical variable as <undefined>.

VariableNames = opts.VariableNames;
opts.SelectedVariableNames =  VariableNames; % select all variables
opts = setvartype(opts,{'Logical','String'},{'logical','string'});
opts = setvaropts(opts,VariableNames,'EmptyFieldRule','auto');
T = readtable(filename,opts)

% In addition to 'missing' and 'auto', you can also set the EmptyFieldRule parameter to 'error'. When you set it to 'error', the readtable function imports empty fields by following the procedure specified in the ImportErrorRule parameter.
% Copyright 2018 The MathWorks, Inc.