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에서 Other Formats에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!