how Modify text file ,Write new values
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hi: I have a text file that is an input file to a simulator program and I want to change some input variables and transfer them back to the simulator program (for example afw in row 48 of column 8), when I do this May_made changes in MATLAB but the text file in the main folder still does not change, please help
filename=fullfile('D:\','app','try1','TRY1B','w2_con.npt ');
fid = fopen(filename,'r');
format = repmat('%s',[1,10]);
A = textscan(fid,format);
A=[A{:}];
fclose(fid);
% Change cell A
A{48,8}=sprintf('%d',6);
0 Commenti
Risposte (1)
Walter Roberson
il 28 Dic 2020
%do not overwrite the old file; we are counting on the old field being 15.0000
filename = fullfile('D:\','app','try1','TRY1B','w2_con.npt ');
newfile = fullfile('D:\','app','try1','TRY1B','new_w2_con.npt ');
S = regexp( fileread(filename), '\n', 'split');
newval = 6;
S{48} = regexprep(S{48}, '15\.0000', sprintf('%.4f', newval), 'once');
S = strjoin(S, '\n');
[fid, msg] = fopen(newfile, 'w'); %not 'wt'
if fid < 0
error('Failed to open file "%s" for writing because "%s"', newfile, msg);
end
fwrite(fid, S);
fclose(fid);
If you cannot count on the field to replace being a specific value, then you may have to replace by position, which can be a bit tricky as it looks like you might possibly be using fixed width fields (or possibly they are tab separated.)
Your existing code to read the fields is not going to do well on lines such as
WB 1 ET OFF OFF ON OFF 15.0000 2.00000 2.00000 10.0000
as the character fields are permitted to have embedded blanks which you are reading in as separate fields.
0 Commenti
Vedere anche
Categorie
Scopri di più su Characters and Strings in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!