MATLAB Answers


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

Asked by Ahmad Fakih on 12 Apr 2019
Latest activity Edited by Stephen Cobeldick on 13 Apr 2019
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!


Sign in to comment.

1 Answer

Answer by Stephen Cobeldick on 12 Apr 2019
Edited by Stephen Cobeldick on 12 Apr 2019
 Accepted Answer

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});
Repeat for each file:


Show 1 older comment
Also the process should be automated for thousands of txt files, so how can we each time open a new output file without removing the previous one?
"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!)

Sign in to comment.