Import data from text file

1 次查看(过去 30 天)
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 个)

Community Treasure Hunt

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

Start Hunting!

Translated by