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

2 ビュー (過去 30 日間)
sally_wu
sally_wu 2015 年 9 月 27 日
コメント済み: sally_wu 2015 年 10 月 3 日
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).
sally_wu
sally_wu 2015 年 10 月 3 日
All your help and suggestions are appreciated! Taking off my hat!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by