replace a random number in a line of a text file

1 vue (au cours des 30 derniers jours)
sajad mhmzd
sajad mhmzd le 30 Sep 2021
Commenté : sajad mhmzd le 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"

Réponse acceptée

Walter Roberson
Walter Roberson le 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 commentaires
sajad mhmzd
sajad mhmzd le 30 Sep 2021
thanks man
sajad mhmzd
sajad mhmzd le 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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Migrate GUIDE Apps dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by