replace a random number in a line of a text file
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
sajad mhmzd
el 30 de Sept. de 2021
Comentada: sajad mhmzd
el 1 de Oct. de 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 comentarios
Respuesta aceptada
Walter Roberson
el 30 de Sept. de 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)
2 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Migrate GUIDE Apps en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!