MATLAB: How to import a CSV file that has a header and a mix of characters and numbers in MATLAB 7.8 (R2009a)

alphanumericcsvreadMATLAB

I would like to read a Comma Separated Values (CSV) file that contains a header and a mix of characters and numbers:
First Name,Last name,Age
John,Doe,100
Jane,Doe,13
Richard,Roe,50
I receive an error when I try to import this file using CSVREAD since this MATLAB function only supports numeric data types.
Although it is possible to use TEXTSCAN as an alternative, it seems that TEXTSCAN, as compared to FSCANF is more high level file reading function, and I am concerned about the time it takes to handle very large data files. So I would prefer to use FSCANF, which is a lower level file scan routine.

Best Answer

The ability to read alphanumeric data from CSV files using the CSVREAD function is not available in MATLAB.
To workaround this issue, if you are concerned about performance and your data files contain a mix of data-types, consider using lower level file I/O functions provided with MATLAB.
To read a file like the one described above, you could parse out the header information first and then use FGETL to read in the rest of the content:
fid = fopen('sample.csv', 'r');
tline = fgetl(fid);
% Split header
A(1,:) = regexp(tline, '\,', 'split');
% Parse and read rest of file
ctr = 1;
while(~feof(fid))
if ischar(tline)
ctr = ctr + 1;
tline = fgetl(fid);
A(ctr,:) = regexp(tline, '\,', 'split');
else
break;
end
end
fclose(fid);
Refer to the following technical note for an introduction to various File I/O APIs provided with MATLAB: