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.
0 个评论
采纳的回答
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 个评论
Star Strider
2020-5-1
D1 = readmatrix(filename, 'HeaderLines',16);
I opted for readtable because it also imported the column headers.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!