Read text file and load data to an array

336 ビュー (過去 30 日間)
Thanh Cao
Thanh Cao 2018 年 5 月 8 日
コメント済み: Taylor Fulton 2020 年 3 月 3 日
I have a text file contains a variable name and value as showed
variable1 0.00069444
variable2 1440.00
variable3 7200.00
variable4 0.90
variable5 -2.00
variable6 -10.00
variable7 0.0002
variable8 0.00
variable9 90.00
I would like to read this text file and store into an array, for example
A = variable1 0.00069444
variable2 1440.00
variable3 7200.00
variable4 0.90
variable5 -2.00
variable6 -10.00
variable7 0.0002
variable8 0.00
variable9 90.00
Thanks for your help

回答 (3 件)

Guillaume
Guillaume 2018 年 5 月 8 日
A lot simpler
t = readtable('C:\somewhere\somefile.ext', 'ReadVariableNames', false);
that's it. However, I'd then give the column some meaningful names, e.g.:
t.Properties.VariableNames = {'Name', 'Value'};

Ameer Hamza
Ameer Hamza 2018 年 5 月 8 日
編集済み: Ameer Hamza 2018 年 5 月 8 日
If you just want to read the text, then run
data = fileread(filename);
But if you want to extract numeric data, the following code will extract it save it into an array
f = fopen(filename);
data = textscan(f,'%s');
fclose(f);
variable = str2double(data{1}(2:2:end));
instead of accessing it like variable1, variable2,... You can access by using indexing like variable(1), variable(2), .... The array style is MATLAB recommended style and is also much better as compared to giving a different name to each variable.
  4 件のコメント
Taylor Fulton
Taylor Fulton 2020 年 3 月 3 日
No. This spits out values that look nothing like any of the numbers in the text file.
Taylor Fulton
Taylor Fulton 2020 年 3 月 3 日
f = fopen('Class15_voltage');
data = textscan(f,'%s');
fclose(f);
variable = str2double(data{1}(2:2:end));
It functioned a moment ago but spat out numbers from kirby's dreamland. Now it just spits out errors.

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


Thanh Cao
Thanh Cao 2018 年 5 月 8 日
Thank you Guillaume, this is awesome.

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by