Best way to read in CSV file with header

5 views (last 30 days)
I was looking at textread and textscan, but they seem like they won't be useful in my case. I have a 1010 column file, with headers. I need to ignore the first 10 column (only those columns have headers). The number of rows is variable, but probably at least 1000.
If I didn't have headers the load command seems like it would work fine. I don''t want to manually strip the headers off beforehand, so this won't work either.

Accepted Answer

Walter Roberson
Walter Roberson on 7 Nov 2011
There is an undocumented textscan() parameter 'headercolumns' to indicate the number of leading columns on the line to skip. Note for this purpose that "column" is determined using the same criteria used to determine "column" for the rest of textscan().
Possibly this HeaderColumns setting is only implemented if you use the undocumented format string '' (the empty string) which only works when all of the (unskipped) columns are numeric.
HL = 3; %for example
HC = 10; %in your case
result = textscan(fid, '', 'HeaderLines', HL, 'HeaderColumns', HC, 'Delimiter', ',');
If you want more control over your columns or do not like using undocumented parameters, then use an explicit format that throws away the unwanted data:
HL = 3; %for example
HC = 10; %in your case
NF = 1000; %1000 desired fields
lineformat = [repmat('%*s',1,HC) repmat('%f',1,NF)];
result = textscan(fid, lineformat, 'HeaderLines', HL, 'Delimiter', ',');

More Answers (0)

Community Treasure Hunt

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

Start Hunting!