Reading a txt file

조회 수: 3 (최근 30일)
KatherineS
KatherineS 2019년 6월 6일
편집: KatherineS 2019년 6월 7일
Hello, I am trying to get MATLAB to read this file and to import all the values as variables and ignore the lines starting with # and $. However everything I try fails to do this.
# Comments start with #, the rest of the line is ignored
# new section headings start with $
#--------------------------------------------------
$ 1 Simulation parameters
x = t45 # id
y = 20120907 # random number
z = 0.0 # time / s
...
#--------------------------------------------------
$ 2 Orbit parameters
# inc = 0.001 # inclination
# ecc = 0.01 # eccentricity
...
I have tried the code below and many other methods.
Thank you in advance for your help.
fid = fopen('file', 'rt');
filepos = 0;
tline = fgetl(fid);
while ~isempty(tline) && any(strncmp(tline, {'#', '$'}))
filepos = ftell(fid);
tline = fgetl(fid);
end
fseek(fid, filepos, 'bof');
C = textread(fid, '%s' , 'Delimiter', ';');
fclose(fid);

답변 (1개)

Jan
Jan 2019년 6월 6일
편집: Jan 2019년 6월 6일
S = fileread('filename');
C = strsplit(S, char(10));
C(strncmp(C, '$'), 1) = [];
C(strncmp(C, '#'), 1) = [];
C = strtok(C, '#'); % remove trailing comments
Data = struct([]);
for iC = 1:numel(iC)
L = strsplit(C{iC}, '=');
Data.(L{1}) = L{2};
end
Maybe you want to convert everything, which looks like a number to a number?
Data = struct([]);
for iC = 1:numel(iC)
L = strsplit(C{iC}, '=');
Value = str2double(L{2});
if isnan(Value) % No valid convertsion to a number
Data.(L{1}) = L{2};
else
Data.(L{1}) = Value;
end
end
  댓글 수: 1
KatherineS
KatherineS 2019년 6월 7일
Thank you!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by