How do I import a CSV file that has a header and a mix of characters and numbers in MATLAB 7.8 (R2009a)?

1 view (last 30 days)
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.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 3 Nov 2021
Edited: MathWorks Support Team on 4 Nov 2021
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:

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products


Release

R2009a

Community Treasure Hunt

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

Start Hunting!