replace a random number in a line of a text file

1 visualización (últimos 30 días)
sajad mhmzd
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"

Respuesta aceptada

Walter Roberson
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
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 comentarios
sajad mhmzd
sajad mhmzd el 30 de Sept. de 2021
thanks man
sajad mhmzd
sajad mhmzd el 1 de Oct. de 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

Iniciar sesión para comentar.

Más respuestas (0)

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!

Translated by