2
votes

I have a tab delimited text file which contains some data organised into columns with the first row acting as column names such as:

TN Stim Task RT
1   A    A    500.2
2   B    A    569
3   C    A    654

and so on.

I am trying to read this textfile into MATLAB(r2018a) using readtable with

Data1 = readtable(filename);

I manage to get all the data in Data1 table, but the column names are showing as Var1, Var2 etc. If I use Name Value pairs to specify to read first row as column names as in:

Data1 = readtable(filename, 'ReadVariableNames', true);

then I get the column names as the first data row, i.e.

1  A  A  500.2

So it just looks like it is ignoring the first row completely. How can I modify the readtable call to use the entries on the first row as column names?

2
it reads fine in r2018b when I test your sample data - so can you add the matlab version. - matlabgui
r2018a. I will add it to the question as well - ag14
What is the extension for your file name? If it is non-standard, you may have to add 'FileType', 'text' to your call to readtable. - gnovice
.txt. Is that non-standard? - ag14
No, that's standard. It loads fine for me in R2016b. - gnovice

2 Answers

2
votes

I figured it out. It appears there was an additional tab in some of the rows after the last column. Because of this, readtable was reading it as an additional column, but did not have a column name to assign to it. It seems that if any of the column names are missing, it names them all as Var1, Var2, etc.

1
votes

Based on the way your sample file text is formatted above, it appears that the column labels are separated by spaces instead of by tabs the way the data is. In this case, readtable will assume (based on the data) that the delimiter is a tab and treat the column labels as a header line to skip. Add tabs between them and you should be good to go.

Test with spaces between column labels:

% File contents:
TN Stim Task RT
1   A   A   500.2
2   B   A   569
3   C   A   654

>> Data1 = readtable('sample_table.txt')

Data1 = 

    Var1    Var2    Var3    Var4   % Default names
    ____    ____    ____    _____

    1       'A'     'A'     500.2
    2       'B'     'A'       569
    3       'C'     'A'       654

Test with tabs between column labels:

% File contents:
TN  Stim    Task    RT
1   A   A   500.2
2   B   A   569
3   C   A   654

>> Data1 = readtable('sample_table.txt')

Data1 = 

    TN    Stim    Task     RT  
    __    ____    ____    _____

    1     'A'     'A'     500.2
    2     'B'     'A'       569
    3     'C'     'A'       654