replace a random number in a line of a text file
2 views (last 30 days)
Show older comments
sajad mhmzd
on 30 Sep 2021
Commented: sajad mhmzd
on 1 Oct 2021
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"
0 Comments
Accepted Answer
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
newvalue = string(10*randn(1,1))
newS = regexprep(S, '(?<=x coordinate = )(-?[\d.]+)', newvalue)
[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)
dbtype(outfilename)
More Answers (0)
See Also
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!