MATLAB: Combine many txt format files with a single column into one file

MATLABtext file

I have A, B, C, D, E file in txt format each of them contain one column with numbers i.e:
  • A*
0.05
0.059
0.1
. . .
0.011
Now I want to combine all these five files into one and have five columns with a one file. How can I do that?

Best Answer

Here is a concise way:
files = {'A.txt', 'B.txt', 'C.txt', 'D.txt', 'E.txt'} ;
buffer = cell( size( files )) ;
for k = 1 : numel( files )
buffer{k} = sscanf( fileread( files{k} ), '%f' ) ;
end
fId = fopen( 'Merged.txt', 'w' ) ;
fprintf( fId, '%f\t%f\t%f\t%f\t%f\r\n', horzcat( buffer{:} ).' ) ;
fclose( fId ) ;
You will have to tailor the formatSpec '%f\t%f\t%f\t%f\t%f\r\n' to your needs, i.e. define a more specific numeric format (e.g. %.3f instead of %f) and define the separator (here \t for tab, but you may need/want a simple comma instead).