merge and displace the data and save into txt file
조회 수: 14 (최근 30일)
이전 댓글 표시
Hi all,
I have a file full of ascii data with 6 columns (col1 is day, col2 is month, col3 is year and col4 to col6 are data). I would like to create the txt.file as below format by using matlab. Each column was separated by tab. (please see attached file for data)
ABCDEFGH
Date name1 name2 name3
19800101 0.5249 11.1333 1.0302
19800102 0.0460 10.8523 1.0302
19800103 0.0692 12.0476 1.0302
...
20071231 0.0649 13.4099 1.0491
Could someone please help and code this in Matlab? Thanks so much.
NAM
댓글 수: 0
채택된 답변
Geoff Hayes
2014년 11월 20일
inputData=importdata('data.txt');
You can then build the output matrix as
outputData = [ inputData(:,3)*10000+inputData(:,2)*100+inputData(:,1) inputData(:,4:6)];
The above just "builds" the first column of outputData by summing the year, month, and day columns from inputData, and then concatenates that result with the final three columns.
To save this to file, just do something like
dlmwrite('myOutput.txt',outputData,'precision','%d','delimiter','\t');
You can adjust the precision as you see fit. The above will write the following to your text file
...
20071229 3.113964e-02 1.274519e+01 1.049144e+00
20071230 6.487198e-02 1.340989e+01 1.049144e+00
20071231 6.487198e-02 1.340989e+01 1.049144e+00
댓글 수: 2
Geoff Hayes
2014년 11월 20일
Nam's answer moved here
Thanks Geoff Hayer for your helping.
There are very useful scripts. But I have 2 questions such as:
1. I did as you suggest about adjustment the precision by use the script:
dlmwrite('myoutput.txt',outputData,'precision',5, 'delimiter','\t');
It should be adjusted all the value. How do I only adjust last 3 values?
2. How do I add the 2 text lines above these data into text file?
THIS IS DATA FOR ANALYSIS
Date value1[kg/m3/s] value2[kg/m3/s] value3[kg/m3/s]
Thanks
NAM
Geoff Hayes
2014년 11월 20일
Nam - if you want to add the additional text and set the formatting for each column, then you will have to use fopen and fprintf to write the data to file. Try the following
% open the file for writing
fid = fopen('myoutput.txt','wt');
if fid>0
fprintf(fid,'THIS IS DATA FOR ANALYSIS\n');
fprintf(fid,'Date\tvalue1[kg/m3/s]\tvalue2[kg/m3/s]\tvalue3[kg/m3/s]\n');
fprintf(fid,'%d\t%.5f\t%.5f\t%.5f\n',outputData');
% close the file
fclose(fid);
end
추가 답변 (1개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!