use matlab to process a txt file

1 view (last 30 days)
Wenjie
Wenjie on 6 Mar 2015
Edited: Image Analyst on 7 Mar 2015
The situation is this. There is a txt file generated by a scientific software containing lots of information line by line. Some parameters are not optimized well by that software and thus I have to optimize them in matlab. Then I have to make a another txt file the same as the previous one except some parameters are not the same.
So the main task is to use the matlab function 'fprint' to print the content of the txt file. For instance, the txt is like this:
line 1: blablabla......
line 2: blablabla......
line 3: blablabla......
......
line 100: blablabla......
To make this file, my matlab code is like this:
fprintf(file, 'line 1: blablabla...... \n');
fprintf(file, 'line 2: blablabla...... \n');
fprintf(file, 'line 3: blablabla...... \n');
......
fprintf(file, 'line 100: blablabla...... \n');
I just simply copy and paste every line in the txt file to every corresponding line of the 'fprintf' command. But txt file contains thousands of lines. It's too cumbersome to repeat the process of copy and paste again and again. So my question is ; Is there any way to make matlab read the txt file line by line and use a loop to generate 'fprintf' like this: fprintf(file, 'line 1: blablabla...... \n');

Accepted Answer

Stephen23
Stephen23 on 6 Mar 2015
Edited: Stephen23 on 6 Mar 2015
Sure. Write a loop and use fgetl to read the data, and use fprintf to print to another file. The documentation gives this example:
fid = fopen('fgetl.m');
tline = fgetl(fid);
while ischar(tline)
disp(tline)
tline = fgetl(fid);
end
fclose(fid);
Note that you you should read and write to different files, as the size of the data might change, so you might end up with something a bit like this:
fidR = fopen(sourcefilename,'rt');
fidW = fopen(destinationfilename,'wt');
tline = fgetl(fidR);
while ischar(tline)
... make whatever changes you need to tline
fprintf(fidW,'%s\n',tline);
tline = fgetl(fidR);
end
fclose(fidR);
fclose(fidW);
  1 Comment
Wenjie
Wenjie on 6 Mar 2015
Edited: Image Analyst on 7 Mar 2015
Good answer. But maybe I didn't explain it clearly enough. For instance, the content in the original .txt file is like this:
line 1:XXXXXX
line 2:XXXXXX
......
line n:XXXXXX
The final goal is to use matlab to generate a a .txt file or preferably an .m file with each line written like this:
fprintf(file, 'line 1:XXXXXX \n');
fprintf(file, 'line 2:XXXXXX \n');
......
fprintf(file, 'line n:XXXXXX \n');
Simply speaking, I want to make an .m file starting with fprintf, with the argument in fprintf the same as the original content in the txt file.

Sign in to comment.

More Answers (0)

Categories

Find more on Animation 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!