MATLAB: Do I receive an error when I try to create a dataset from the tab-delimited file in MATLAB 7.8 (R2009a)

MATLAB

I use the command below to create a dataset from my tab-delimited file:
A = dataset('File', filename, 'delimiter', '\t', 'ReadVarNames', 'off');
and I receive the following error:
??? Error using ==> tdfread at 133
Requires the same number of delimiters on each line.
Error in ==> dataset.dataset>readFile at 465
s = tdfread(file,delimiter,false,readvarnames,treatasempty);
Error in ==> dataset.dataset>dataset.dataset at 244
a = readFile(a,fileArg,otherArgs);
I have been able to identify that this error occurs because the file contains an extra delimiter at the end of each line.

Best Answer

This is a limitation in the TDFREAD function in the way that it tries to ensure that the file has the same number of data columns on each row. It assumes that there should be (number_of_variables-1) delimiters in each row, therefore, the extra delimiter at the end of each row in this file results in an error message.
You can workaround this issue by using IMPORTDATA to read the data from the file, and then constructing the dataset from this data. For example:
%Read the data
B = importdata(filename);
%Split each column of data into a separate cell in a cell array
C = mat2cell(B, size(B,1), ones(1, size(B,2)))
%Construct the dataset
A = dataset(C{:})
As an alternative solution, you could also specify the format string for reading the file, assuming you know the number of columns of data within the file. For example, to create a dataset from a file with five numeric columns, execute:
A = dataset('File',filename, '%f%f%f%f%f',...
'delimiter', '\t', 'ReadVarNames', 'off');