Converting txt file into title and array?

1 回表示 (過去 30 日間)
Darren Miller
Darren Miller 2020 年 5 月 12 日
コメント済み: Darren Miller 2020 年 5 月 13 日
I am trying to load a txt file that looks like this:
Time (s)
0
1.5
1.6
2
2.5
3.5
4
and I want to save the first line as a string to be used for the xlabel on a plot, and the n lines of numbers afterwards I would like to save as an array.
I tried to use something like this and it did not work:
xL = fscanf(fid,'%s');
fgetl(fid); %first line of txt file is the data label I am going to use for the plot xlabel
for n = 1:dataLength % dataLength = 7 here
data(n) = fscanf(fid,'%f');
fgetl(fid);
end
The problem was the xL variable was then defined as 'Time (s)01.51.622.53.54' . It basically did not just grab one line for some reason.

採用された回答

per isakson
per isakson 2020 年 5 月 12 日
編集済み: per isakson 2020 年 5 月 12 日
Try this
%%
fid = fopen( 'cssm.txt', 'rt' );
xL = fgetl( fid ); % read the first line
data = fscanf( fid, '%f' ); % read numerical data until end of file
[~] = fclose( fid );
%%
xL
data
where cssm.txt contains your data sample
  1 件のコメント
Darren Miller
Darren Miller 2020 年 5 月 13 日
Thank you! This works perfectly.

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

その他の回答 (1 件)

Ameer Hamza
Ameer Hamza 2020 年 5 月 12 日
On recent MATLAB releases, you can also try readtable
t = readtable('test.txt', 'PreserveVariableNames', true);
Then access data and label using this syntax
data = t{:,1}
label = t.Properties.VariableNames{1}
  1 件のコメント
Darren Miller
Darren Miller 2020 年 5 月 13 日
This almost works perfectly, but unfortunately my txt file header has parentheses in it ( 'Time (s)') which did not get preserved for some reason. Thanks anyway though, I appreciate the help!

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

カテゴリ

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