Scan a data file for data after keywords

조회 수: 6 (최근 30일)
Moritz Schäfle
Moritz Schäfle 2022년 4월 13일
댓글: DGM 2022년 4월 26일
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

채택된 답변

DGM
DGM 2022년 4월 13일
편집: DGM 2022년 4월 13일
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
Moritz Schäfle
Moritz Schäfle 2022년 4월 25일
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 2022년 4월 26일
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.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by