MATLAB: How to replace data in a specific address in a text file with new modified data

matrixtext filetextscan

Hi there! I have a problem with editing series of numbers that are located in a specific address in a text file. First I extracted series of numbers from that text file, then I have modified them and finally put them in a new matrix B. here is code which I have written.
inp= fopen('DEY.inp','r+');
A= textscan(inp,'%s %d %d %d','headerlines', 144); %read text file and put it in A, ignor first 144 lines
B = zeros(1,41);
X=1.5;
for k=1:41
B(1,k) = X*A{1,2}(k,1);% multiply numbers located in a specific address of A and put them in B matrix
end
now I have to return modified numbers that I have put in matrix B, to the same address of the same text file (DEY.inp). I mean that numbers located in a specific address of DEY.inp must be precisely replaced with numbers multiplie by X. How is it possible? with fprintf maybe? I have attached my text file with .txt format..

Best Answer

Looking at your uploaded data file, I think one possible solution would be like this.
% Read all lines in text file
fid = fopen('DEY.txt','r');
txtData = textscan(fid,'%s','Delimiter','\n');
fclose(fid);
txtData = txtData{1};
% Target lines
idx = false(size(txtData));
idx(145:185) = true;
% Multiply 2nd column of the target line by X
X = 1.5;
[c1,c2] = split(txtData(idx));
c = cell(size([c1,c2]));
c(:,1:2:end) = c1;
c(:,2:2:end) = c2;
val = str2double(c(:,3));
c(:,3) = arrayfun(@num2str,val*X,'UniformOutput',false);
txtData(idx) = join(c);
% Save as DEY2.txt
fid = fopen('DEY2.txt','w');
fprintf(fid,'%s\n',txtData{:});
fclose(fid);