How to edit a number in a text file and save a copy of the file multiple times?

2 ビュー (過去 30 日間)
Ahmad Fakih
Ahmad Fakih 2019 年 4 月 12 日
編集済み: Stephen23 2019 年 4 月 13 日
Dear Members,
I need to do a probabilisitc analysis where I will be generating thousands of input text files, they all will be the same except the 2 numbers in the red circle below will change each time (the 2 numbers will be replaced by another 2 numbers from a vector). Can you please suggest a method for editing these 2 numbers in MATLAB and saving them in a new text file copy?
(You can find the text file attached)
Thank you!
Capture1.PNG

採用された回答

Stephen23
Stephen23 2019 年 4 月 12 日
編集済み: Stephen23 2019 年 4 月 12 日
vec = [23,5]; % new values
cnt = 0;
rgx = '^(\s*\S+\s+)(\S+)(.+gamma.+)$';
f1d = fopen( 'input_matlab.txt','rt');
f2d = fopen('output_matlab.txt','wt');
while ~feof(f1d)
str = fgetl(f1d);
tkn = regexp(str,rgx,'once','tokens');
if ~isempty(tkn)
cnt = cnt+1;
str = sprintf('%s%#.14E%s',tkn{1},vec(cnt),tkn{3});
end
fprintf(f2d,'%s\n',str);
end
fclose(f1d);
fclose(f2d);
Repeat for each file:
  4 件のコメント
Stephen23
Stephen23 2019 年 4 月 13 日
編集済み: Stephen23 2019 年 4 月 13 日
"But can you please elaborate what does this line mean?"
That line defines a regular expression. Regular expressions are a special language for parsing strings by matching specific substrings or character types. It matches:
rgx = '^(\s*\S+\s+)(\S+)(.+gamma.+)$';
% ^ start of the string.
% ( start of token 1.
% \s* zero or more whitespace characters.
% \S+ one or more non-whitespace chars.
% \s+ one or more whitespace char.
% ) end of token 1.
% ( start of token 2.
% \S+ one or more non-whitespace char (i.e. the number you want)
% ) end of token 2.
% ( start of token 3.
% .+ one or more char.
% gamma the word "gamma"
% .+ one or more char.
% ) end of token 3.
% $ end of the string.
The word "gamma" only occurs on the lines that you want to match. The second token matches the number that you want to change. The first and third tokens match everything else on the line, before and after that number. The code simply replaces the second token, everything else from the file remains exactly the same.
You can learn about regular expressions here:
"Also the process should be automated for thousands of txt files"
Read the link that I gave you. Use sprintf to generate the file names, and change the name used in fopen (for the output file!)
Ahmad Fakih
Ahmad Fakih 2019 年 4 月 13 日
Thanks a lot!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Import and Export についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by