MATLAB Answers

Scanning a txt file

4 views (last 30 days)
Mohamad Dabdoub
Mohamad Dabdoub on 26 May 2021
Answered: Allen on 26 May 2021
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 Comment
Scott MacKenzie
Scott MacKenzie on 26 May 2021
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?

Sign in to comment.

Answers (1)

Allen on 26 May 2021
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');
% 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));


Community Treasure Hunt

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

Start Hunting!