フィルターのクリア

How to skip lines after the header line when using readtable

215 ビュー (過去 30 日間)
Fyodor Tatarinov
Fyodor Tatarinov 2021 年 6 月 3 日
編集済み: Stephen23 2021 年 6 月 3 日
I have csv files where 1st row is always names of variables 2nd row is units (needs to be skiped) and further rows are data to read. Number of columns and column names may differ in different files. I want to read each file with the column names and keep the data in table format. In the description of readtable function I found only the option to skip first n lines, then to read header from (n+1)th line and the data since next line, but I did not find the option to start to read data 2 lines after header.
So, I did such a trick with reading first header line by fgetl, then reading data by readtable since line 3 and then replacing variable names by previously red titles:
fid = fopen(strcat(pathname,eddyDir.name{f}));
tmp = fgetl(fid); % reading 1st header line
xini = readtable(strcat(pathname,eddyDir.name{f}),'HeaderLines',2); % input data for current year
fclose(fid);
j = 0; % parsing header line
while true
j = j+1;
[titles{j}, tmp] = strtok(tmp, ',');
if isempty(titles{j}), break; end
end
xini.Properties.VariableNames = titles;
Maybe there is more fine way to do it?
Thanks

採用された回答

Stephen23
Stephen23 2021 年 6 月 3 日
編集済み: Stephen23 2021 年 6 月 3 日
type test.csv
A,B,C cat,in,hat 11,12,13 21,22,23 31,32,33 41,42,43
opts = detectImportOptions('test.csv');
opts.DataLines = 3;
opts.VariableNamesLine = 1;
T = readtable('test.csv',opts)
T = 4×3 table
A B C __ __ __ 11 12 13 21 22 23 31 32 33 41 42 43
  2 件のコメント
Scott MacKenzie
Scott MacKenzie 2021 年 6 月 3 日
@Stephen Cobeldick Thanks. This is clearly the correct solution. I deleted my miscued attempt. @Fyodor Tatarinov here's your answer. :) Good luck.
Fyodor Tatarinov
Fyodor Tatarinov 2021 年 6 月 3 日
Thanks a lot!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSpreadsheets についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by