Combine many txt format files with a single column into one file
2 次查看(过去 30 天)
显示 更早的评论
采纳的回答
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
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 Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!