How to import txt files with variable column number with textscan ?

18 ビュー (過去 30 日間)
Jane
Jane 2014 年 11 月 5 日
回答済み: Jane 2014 年 11 月 6 日
I use textscan to import txt files mixed with string and numbers. Usually these files have 50 columns. The first line is the header. I can make the string column the last column in the data file. My code is below. Now the data files vary in column numbers. I can check the tokens size for the column numbers. But I don't know how to make my text scan more flexible to handle variable column sizes.
fid = fopen(filename,'rt');
tline = fgetl(fid);
tokens = regexp(strtrim(tline), ',', 'split');
a = textscan(fid,'%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%q','Delimiter',',','EmptyValue',NaN);
fclose(fid);
Thank you, Jane

採用された回答

per isakson
per isakson 2014 年 11 月 5 日
編集済み: per isakson 2014 年 11 月 5 日
"check the tokens size for the column numbers" &nbsp thus
ncol = number_of_columns
and
a = textscan( fid, [ repmat('%f',[1,ncol-1]), '%q' ] ...
, 'Delimiter',',', 'EmptyValue',NaN );
and why not use
'CollectOutput', true

その他の回答 (1 件)

Jane
Jane 2014 年 11 月 6 日
Thank you, per isakson. I know there must be an easy way instead of putting 50 %f. Thank you, it is very helpful.

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by