replace a random number in a line of a text file

2 ビュー (過去 30 日間)
sajad mhmzd
sajad mhmzd 2021 年 9 月 30 日
コメント済み: sajad mhmzd 2021 年 10 月 1 日
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"

採用された回答

Walter Roberson
Walter Roberson 2021 年 9 月 30 日
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 件のコメント
sajad mhmzd
sajad mhmzd 2021 年 9 月 30 日
thanks man
sajad mhmzd
sajad mhmzd 2021 年 10 月 1 日
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

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMigrate GUIDE Apps についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by