Change line in a text file
4 views (last 30 days)
Show older comments
Hello,
I have a text file where different reactions are written as well as their kinetics constants para1 para2 para3
For example:
A+ B => C + D para1 para2 para3
This text file is read by another software that solves a set of equations. I need to test out different values for each parameter para1 para2 and para3. These parameters are in the second to last line of the text file. It’s a very big text file and I don’t want matalb to read and then rewrite everything each time. I want to do this in a loop and for every iteration I test out a different value for each parameter (so the values written on the text file are not always the same). Does anyone know how I can do this?
Thanks
10 Comments
Jan
on 5 Jun 2018
Edited: Jan
on 5 Jun 2018
It is still not clear to me, what "correspond" means here:
A3+ B3 => C + D para31 para32 para33
Which corresponds to
C2H2 => 2C + H2 3E6 0 40E3
But I've forgot the 'w' flag in the fopen command. Without it, fopen tries to open the file for reading. When the file does not exist, the fopen fails. With 'w' the file is opened for writing. 'w+' allows reading and writing and is not useful here.
It is better to use the message in case of errors:
[fid, msg] = fopen('Test2.txt', 'w');
if fid == -1
error('Cannot open file: %s', msg);
end
I've fixed my answer and inserted the 'w' specifier.
By the way: Do not get confused by questions for clarifications. The purpose of this forum is to solve Matlab problems. It is the nature of problems, that not all details are clear initially. Even if I'm probing, the goal is to solve your problem.
Answers (1)
Jan
on 4 Jun 2018
Edited: Jan
on 5 Jun 2018
If the file has 500 lines only, importing the complete file and creating a new one is cheap an easy. Note that 500 lines of text are a lot of work for a human, but a cookie for a computer.
CStr = strsplit(fileread(FileName), '\n');
index = strcmp(CStr, 'A2+ B2 => C + D para21 para22 para23'); % [EDITED]
for i = 1:4
CStr{index} = sprintf('A2+ B2 => C + D %d %d %d', P1(i), P2(i), P3(i));
fid = fopen(fullfile(tempdir, 'OutputFile.txt'), 'w'); % [EDITED 2]
if fid == -1
error('Cannot open file.');
end
fprintf(fid, '%s\n', CStr{:});
fclose(fid);
... Launch software
end
Here I guess, that P1 etc is a numerical array. If this does not match, please explain the details.
4 Comments
Jan
on 4 Jun 2018
Edited: Jan
on 4 Jun 2018
Now I'm guessing what "explained above" exactly means. Please post the code you are using and a copy of the complete error message.
If you did not meant
'A2+ B2 => C + D para21 para22 para23'
but a line, which starts with
'A2+ B2 => C + D '
use:
index = strncmp(CStr, 'A2+ B2 => C + D ', 16);
or whatever is suitable to identify the line you want to replace.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!