Issues with readtable()

20 views (last 30 days)
Salsabil Salah
Salsabil Salah on 21 Aug 2019
Edited: Adam Danz on 22 Aug 2019
Hello, I have been trying to import excel data files using GUI. I used
[a,b] = uigetfile;
t = readtable(fullfile(b,a));
t gets uploaded as a a table but the empty cells in the excel file appear as NaN in table t. How do I prevent this.
For some reason readcell, readvars dont work for me
I have also tried fillmissing but I get this
x = fillmissing(t,'constant',0)
Error using fillmissing/checkArrayType (line 552)
Invalid fill constant type.
Please help me!

Answers (1)

Adam Danz
Adam Danz on 22 Aug 2019
Edited: Adam Danz on 22 Aug 2019
" the empty cells in the excel file appear as NaN in table t. How do I prevent this?"
NaNs: leave 'em or keep 'em?
NaNs are an indicator that numeric data are missing from your spreadsheet or the data was imported improperly. The first thing to do is check that the NaN values in Matlab are indeed from empty cells in the spread sheet. If that's the case, there's no pre-packaged solution for missing data. Most of the time keeping the NaN values is the best option rather than replaceing them with some arbitrary number.
One problem with replacing the NaNs with an arbitrary number is that it will invalidate computations such as mean(), diff() and almost any other function. Another problem is that unless you choose a highly improbable number (-9999) you'll never know if the value is actual data or was inserted to replace a NaN.
Many matlab functions ignore NaNs or have flags that can be set in order to ignore NaNs. You can also create your own mask when the NaNs need to be ignored.
data(~isnan(data))
Replacing NaNs in a table
That being said, here's how to fill the NaNs in your table with a constant. You need to use a cell array where every element defines the fill value for each column of the table. Numeric and character columns need to have a numeric and character fill value.
The first line identifies which columns are numerc and assumes the rest are char. It then assigns 0 for numeric fills and '' for char fills.
isnum = varfun(@isnumeric,T,'output','uniform'); % logical vector that ID's numeric columns
fillVal = repmat({''},size(isnum));
fillVal(isnum) = {0};
T2 = fillmissing(T,'Constant',fillVal) % Fill the missing data

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!