MATLAB: Overwriting specific line in a text file and data export

data exportMATLAB

Hello,
I'm having trouble trying to export the data from my code into the following format, 'FLUX FACTORS.txt.' Its easy enough to just export the data as a text file, but the problem is is that the program I plan to use this file as an input for requires that I keep the same formatting as 'FLUX FACTORS.txt' (it was based on punch cards).
How do I export the data in my code variable FLUX and have it follow the same configuration as 'FLUX FACTORS.txt.'
Secondly, how can I overwrite a single line from 'HISTORY.txt' (specifically line 3) and overwrite it with my data from 'FLUX FACTORS.txt.' e.g. for one run, I'd like to replace line 3 in 'History.txt' with line 5 from 'FLUX FACTORS.txt.'
I have attached my code and the input files below.
Thanks in advance,
Quang

Best Answer

file1 = 'FLUX FACTORS.txt' ;
file2 = 'HISTORY.txt' ;
% REad file1
fid = fopen(file1,'r') ;
S1 = textscan(fid,'%s','delimiter','\n') ;
S1 = S1{1} ;
fclose(fid) ;
% REad file2
fid = fopen(file2,'r') ;
S2 = textscan(fid,'%s','delimiter','\n') ;
S2 = S2{1} ;
fclose(fid) ;
% Replace 3rd line of file2 with 5th lines of file1
S2{3} = S1{5} ;
% Write the edited to file
fid = fopen('data.txt','wt') ;
fprintf(fid,'%s\n',S2{:});
fclose(fid);