How can I replace data in a specific address in a text file with new modified data?

4 views (last 30 days)
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..

Accepted Answer

Akira Agata
Akira Agata on 12 Jan 2019
Edited: Akira Agata on 12 Jan 2019
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);
  3 Comments
Akira Agata
Akira Agata on 13 Jan 2019
Dear Kamyar-san,
Thank you for your reply. I believe that is a carriage return problem. To fix it, please modify the last part of the program as follows:
% Save as DEY2.txt with carriage return
fid = fopen('DEY2.txt','w');
fprintf(fid,'%s\r\n',txtData{:});
fclose(fid);

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!