Import data from text file

2 ビュー (過去 30 日間)
Miguel Cardoso
Miguel Cardoso 2020 年 4 月 30 日
コメント済み: Star Strider 2020 年 5 月 1 日
Hi!
I am trying to import some data automatically from a text file.
filename = 'textfile.dat';
delimiterIn = '';
headerlinesIn = 15;
variable = importdata(filename,delimiterIn,headerlinesIn);
save variable
load('variable.mat');
Unfortunatelly this is not working and I do not know why this does not make sense.
Can anyone help me?
I will leave my text file attached.

採用された回答

Star Strider
Star Strider 2020 年 4 月 30 日
That file is not easy to read, however it’s not impossible.
It needs to be read in two stages. There might be easier ways to read it, however this works, although it may not work for all such files, unless they have exactly the same structure:
filename = 'textfile.dat';
Txt = fileread(filename);
HeaderTextEnd = strfind(Txt,'IT');
HeaderText = Txt(1:HeaderTextEnd-10);
then use one of these, depending on the MATLAB version you have:
T1 = readtable(filename, 'HeaderLines',16, 'PreserveVariableNames',1); % With R2019b & Later
T1 = readtable(filename, 'HeaderLines',16, 'ReadVariableNames',0); % With R2013b To R2019a
producing:
HeaderText =
'
*******************************************************************************
<XCPLTENSOR>
Isotropic exchange couplings Jij
number of sites NQ = 8
number of types NT = 16
site occupation:
1 2 1 1.000 2 0.000
2 2 3 1.000 4 0.000
3 2 5 1.000 6 0.000
4 2 7 1.000 8 0.000
5 2 9 0.000 10 1.000
6 2 11 0.000 12 1.000
7 2 13 1.000 14 0.000
8 2 15 1.000 16 0.000'
and ‘T1’ as a (98848x15) table.
I only looked at the first several rows, and they appeared to be correct. I assume everything else was imported successfully.
Note that 'PreserveVariableNames' will provide them only for information. They cannot be used to reference the variables because they are not appropriate MATLAB variable names. It will be necessary to refer to them by their column assignments instead.
  2 件のコメント
Miguel Cardoso
Miguel Cardoso 2020 年 5 月 1 日
There is any way to import it as a numeric matrix instead of a table?
Star Strider
Star Strider 2020 年 5 月 1 日
Yes. Use readmatrix (introduced in R2019a) instead:
D1 = readmatrix(filename, 'HeaderLines',16);
I opted for readtable because it also imported the column headers.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by