MATLAB: Use matlab to process a txt file

txt fprintf

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');

Best Answer

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);