How can I read a csv file which has multiple header lines, a line for variable names and a line for units?

109 views (last 30 days)
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

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 23 Feb 2017
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: {}
 
  1 Comment
Mike D.
Mike D. on 30 Aug 2020
What if the header name has a space in it? This causes a mismatch between headers and the column data. For example, what if the first column was "Phase Time" instead of "Time". It associates "Phase" with column 1 and "Time" with column 2, but I want "Phase Time" with column 1. How do I do this? Thanks

Sign in to comment.

More Answers (0)

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!