replace a random number in a line of a text file
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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"
0 commentaires
Réponse acceptée
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
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)
Plus de réponses (0)
Voir également
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!