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

5 views (last 30 days)
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?

Accepted Answer

Cedric
Cedric on 27 Sep 2015
Edited: Cedric on 27 Sep 2015
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).
  5 Comments
Cedric
Cedric on 28 Sep 2015
Edited: Cedric on 28 Sep 2015
To add to what was already said, this is a string called format spec, which is passed to FPRINTF to define the format of what this function must output. It is a common way to define what and how to print something, or what and how to read something (S/FSCANF). It is usually used for printing variables content to the standard output (the command window), e.g.
a = 8 ;
b = 4.5 ;
fprintf( '%d, %f\n', a, b ) ;
Output:
8, 4.500000
Here you see that there are two format operators in the format spec, %d (print integer) and %f (print float) that will be applied to the two variables that are passed to FPRINTF after the format spec in the same order ( %d will be applied to the content of variable a, and %f to the content of variable b). The last \n codes for new line.
This is pretty standard. Now the less standard part is illustrated below:
a = [1,2,3,4] ;
fprintf( '%d %d\n', a ) ;
Output:
1 2
3 4
Here you see that the format spec (output 2 integers and a new line) was repeated as many times as needed for "eating" ;-) all elements of array a. This allows to output many lines with a single call to FPRINTF and this is what I implemented in my solution. Note that the array is read column-wise and this is why we transpose the output of HORZCAT (n x 5 -> 5 x n).
sally_wu
sally_wu on 3 Oct 2015
All your help and suggestions are appreciated! Taking off my hat!

Sign in to comment.

More Answers (0)

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!