MATLAB: Edit entries in textfile with fopen

MATLABtext file

I need help while editing a control file of LS-DYNA via Matlab. In the following picture the structure of my file is depcited.
I need to change the entry in row number 12 to a specific value. I usually generate my output files with:
fileID = fopen(filename,permission);
fprintf(fileID, '...');
fclose(fileID);
However in this specific case this wont work, because depending on the permission, matlab discardes existing content or just adds new content to the end of the file.
My question is: What is the best way to open the file and edit an entry in a specific location? Performance matters…
Thanks for your help!
Kind regards

Best Answer

Hi,
One way to to do this.
Read the whole contents of your file in one cell.
Modify the line you want (be careful to keep the syntax).
rewrite the textfile with the new cell.
% read the data
fid = fopen('Myfile.txt','r');
MyText = textscan(fid,'%s','delimiter','\n');
fclose(fid);
%reconcatenate in a cell
MyText = [MyText{:}];
% Modify the content : here, the 12th line, new string.
MyText{12} = '2.3';
% rewrite the file
fid = fopen('Myfile.txt','wt');
fprintf(fid,'%s\n',MyText{:});
fclose(fid);
You can't really just specify a line to modify.