replace a random number in a line of a text file
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
sajad mhmzd
am 30 Sep. 2021
Kommentiert: sajad mhmzd
am 1 Okt. 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 Kommentare
Akzeptierte Antwort
Walter Roberson
am 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)
2 Kommentare
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!