Scanning a txt file

조회 수: 1 (최근 30일)
Mohamad Dabdoub
Mohamad Dabdoub 2021년 5월 26일
답변: Allen 2021년 5월 26일
Hi all,
I have a txt file that contains the information as following;
Nodnr DtX DtY DtZ
38969 5.794E-03 8.145E-02 2.575E-03
83994 5.120E-03 9.339E-02 1.662E-04
91447 5.413E-03 8.755E-02 5.545E-04
94611 3.502E-03 8.343E-02 2.779E-03
96884 4.868E-03 9.408E-02 -6.649E-05
97051 3.808E-03 9.157E-02 -9.605E-04
This short table is repeated many times. From each short table, I want to extract the values corresponding to each Nodnr (so each node will have the DtX,DtY, and DtZ), that will be later used for computations and other calculations automatically.
  댓글 수: 1
Scott MacKenzie
Scott MacKenzie 2021년 5월 26일
It is not clear what you mean by "is repeated many times". Is the table repeated many times in the same file? If so, is the header line also repeated? Or, is the table repeated many times, but in different files?

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

답변 (1개)

Allen
Allen 2021년 5월 26일
Mohamad,
A solution to your question has been provided in an older thread. See the link below for more details.
% Assign expression for the string in the header line(s). Assumes that they
% are tab delimited names. Can be written more directly, but wanted this to
% easy to adjust for other delimiters.
header = strjoin(["Nodnr","DtX","DtY","DtZ"],","); % Use "\t" for tab-delimiters
% Reads all lines as strings
fileID = fopen(filename);
C = textscan(fileID,'%s','Delimiter','\r');
fclose(fileID);
% Get index for lines that do not contain the header string
idx = ~contains(C{1},header);
% Uses textscan to read each line of floating-doubles and comma delimiters,
% then converts cell-arrays to numerical-arrays and combines them into a
% single numerical-array.
num = cell2mat(cellfun(@(x) cell2mat(textscan(x,'%f','Delimiter',','))',C{1}(idx),'un',0));

카테고리

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