Import data from text file
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Miguel Cardoso
il 30 Apr 2020
Commentato: Star Strider
il 1 Mag 2020
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.
0 Commenti
Risposta accettata
Star Strider
il 30 Apr 2020
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 Commenti
Star Strider
il 1 Mag 2020
D1 = readmatrix(filename, 'HeaderLines',16);
I opted for readtable because it also imported the column headers.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Text Files in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!