MATLAB Answers

how to read a table from a CSV file with multiple header

18 views (last 30 days)
Carlos Alonso
Carlos Alonso on 26 May 2020
Commented: Carlos Alonso on 26 May 2020
Hello
I want to read a table from a CSV file that has 2 row header.
Time Speed Temp
s kph degC
1 12 24
2 13 25
3 14 26
How I can read the above table and display it showing the 2 row header.?
I have tried to do on different ways but only 1 row header is shown (see below)
3×3 table
Time Speed Temp
____ _____ ____
1 12 24
2 13 25
3 14 26
However I would like to see table as below
3×3 table
Time Speed Temp
s kph degC
1 12 24
2 13 25
3 14 26

  0 Comments

Sign in to comment.

Answers (1)

Ruger28
Ruger28 on 26 May 2020
Edited: Ruger28 on 26 May 2020
fname = 'MyCSV.csv';
headerlines = 2;
CSV_Data = dlmread(fname,',',headerlines,0); % filename, delimiter, row offset, column offset
% create table with pre-defined headers
TableHeaders = {'Time_s','Speed_kph','Temp_C'};
MyTable = table(CSV_Data(:,1),CSV_Data(:,1),CSV_Data(:,1),'VariableNames',TableHeaders);

  3 Comments

Carlos Alonso
Carlos Alonso on 26 May 2020
Thanks for reply. It does not work. Using your script, the table is converted in a matrix and headers disappear.
CSV_Data =
1 12 24
2 13 25
3 14 26
Ruger28
Ruger28 on 26 May 2020
Yes, sorry about that. I guess I read too fast.
Will you always know the headers, or are they dynamic?
Carlos Alonso
Carlos Alonso on 26 May 2020
Hi , the header will change dynamically, as I will be adding and removing columns. Thanks

Sign in to comment.