replace a random number in a line of a text file
2 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
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
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)
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Migrate GUIDE Apps についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!