필터 지우기
필터 지우기

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

조회 수: 3 (최근 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 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