MATLAB: How to read a csv file which has multiple header lines, a line for variable names and a line for units

detectimportoptionsMATLABreadtable

How can I read a csv file which has multiple header lines, a line for variable names and a line for units? Can everything be read in a single go?
e.g. 
Header Line 1,1,
Header Line 2,2,
Date,2/4/2017,
,,
Time,Var 1,Var 2
Seconds,miles,miles
1,5,78
2,6,7
3,5,8
4,6,78
5,56,788
6,5,8

Best Answer

This can be done using 'readtable' function with import options.
For more information about import options, refer to the following documentation:
https://www.mathworks.com/help/matlab/ref/delimitedtextimportoptions-object.html
Suppose the csv file name is TestFile.csv
 
>> opts = detectImportOptions('TestFile.csv','NumHeaderLines',4); % number of header lines which are to be ignored
>> opts.VariableNamesLine = 5; % row number which has variable names
>> opts.DataLine = 7; % row number from which the actual data starts
>> opts.VariableUnitsLine = 6; % row number which has units specified
>> tbl = readtable('TestFile.csv',opts)
tbl =
Time Var 1 Var 2
____ ______ ______
1 5 78
2 6 7
3 5 8
4 6 78
5 56 788
6 5 8
>> tbl.Properties
ans =
struct with fields:
Description: ''
UserData: []
DimensionNames: {'Row' 'Variables'}
VariableNames: {'Time' 'Var 1' 'Var 2'}
VariableDescriptions: {}
VariableUnits: {'Seconds' 'miles' 'miles'}
RowNames: {}