replace a random number in a line of a text file

2 views (last 30 days)
how can I replace random number (with 'randi()' commond) in a text file? for example I want replace "1.035" in the below line with a random number:
"x coordinate = 1.035"

Accepted Answer

Walter Roberson
Walter Roberson on 30 Sep 2021
In the below, the isunix() branch is to put in example text since I do not have a file to work with. In your actual code, you would just have the fileread() without the if isunix()
filename = 'example.txt';
outfilename = 'modified.txt';
if isunix()
S = sprintf('Number of nodes: 5\nx coordinate = 1.035\ny coordinate = -3.873\n')
else
S = fileread(filename);
end
S =
'Number of nodes: 5 x coordinate = 1.035 y coordinate = -3.873 '
newvalue = string(10*randn(1,1))
newvalue = "1.9462"
newS = regexprep(S, '(?<=x coordinate = )(-?[\d.]+)', newvalue)
newS =
'Number of nodes: 5 x coordinate = 1.9462 y coordinate = -3.873 '
[fid, msg] = fopen(outfilename, 'w');
if fid < 0; error('could not open output file "%s" because "%s"', outfilename, msg); end
fwrite(fid, newS);
fclose(fid)
ans = 0
dbtype(outfilename)
1 Number of nodes: 5 2 x coordinate = 1.9462 3 y coordinate = -3.873
  2 Comments
sajad mhmzd
sajad mhmzd on 1 Oct 2021
I wrote my own code for replacing a Num in a string but there is a problem. in the second loop the number 12 replace with 132 insted of 13 and i've been confused.
F = 'bodyNameRefManager_1.setBodies(new NeoObjectVector(new Object[] {}));';
for i=12:13
str_e = sprintf('bodyNameRefManager_%0.0f',i);
new = regexprep(F,'bodyNameRefManager_(\w)', str_e)
F = new;
end

Sign in to comment.

More Answers (0)

Categories

Find more on Migrate GUIDE Apps in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!