Scan a data file for data after keywords

5 views (last 30 days)
Hello everyone,
I have an output file from a simulation which is not ordered in a specific way and changes depending on the simulation result.
Somewhere in the file, sections like this can be found. They are on the other hand always the same:
Seed number 1 set at time t = 5.00000E-08 s
-------------------------------------------
in the bulk, zp = 51971
Phase: 1 (BCC_A2)
Seed type: 1 (7: 3/19)
Local temperature = 1308.5 K
Undercooling = 445.98 K
Nucleus curvature undercooling = 0.99588 K
Grain number = 76
What I wanted to ask as a MATLAB beginner: How can I search for keywords like "Seed number", "t =", "zp =" and "Undercooling=" and get the values behind them and write them all in a list with 4 columns and the values which belong together in every line.
I suspect that very similar questions have already answered in this forum. However, I was not able to understand how the solutions are supposed to work. I would be very grateful for any help.
Best regards
Moritz

Accepted Answer

DGM
DGM on 13 Apr 2022
Edited: DGM on 13 Apr 2022
I'm sure there are better ways of doing this, but this is one way.
alltext = fileread('testfile.txt');
alltext = split(alltext,newline);
% find numbers
% this only looks for a block of non-whitespace after each prefix
% if you want to be more explicit, you can replace
% [^\s]+ (one or more non-whitespace characters
% with [+-\.\dE]+ (one or more of the characters +-.E or any digit)
% each output is a cell array with one row per line (mostly empty cells)
seednum = regexp(alltext,'(?<=Seed number\s*)[^\s]+','match');
t = regexp(alltext,'(?<=time t =\s*)[^\s]+','match');
zp = regexp(alltext,'(?<=bulk, zp =\s*)[^\s]+','match');
uc = regexp(alltext,'(?<=Undercooling =\s*)[^\s]+','match');
% concatenate
D = [seednum t zp uc];
% this converts cellchar to numeric and implicitly omits empty cells
% this will break if there aren't the same number of matches per column
D = cell2mat(cellfun(@str2double,D,'uniform',false))
D = 4×4
1.0e+04 * 0.0001 0.0000 5.1971 0.0446 0.0001 0.0000 5.1971 0.0446 0.0001 0.0000 5.1971 0.0446 0.0001 0.0000 5.1971 0.0446
  2 Comments
Moritz Schäfle
Moritz Schäfle on 25 Apr 2022
Hi DGM,
I can not say how thankful I am for this. Thank you very much not only for this solution, but for the explanation!
This helped me a great way. I wish you all the best.
Moritz
DGM
DGM on 26 Apr 2022
Glad to hear that. If and when you find that it satisfies your question, you can click "accept" so that it gets moved to the "accepted" queue, hopefully making it more likely to help future readers with a similar question.

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!