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

3 次查看(过去 30 天)
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?

采纳的回答

Cedric
Cedric 2015-9-27
编辑:Cedric 2015-9-27
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 个评论
Cedric
Cedric 2015-9-28
编辑:Cedric 2015-9-28
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).

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Text Data Preparation 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by