MATLAB: How to read a.txt file in matlab

txtread

I want to ask about how to read a .txt file, for example:
# Contents of table U_WMC.GTS_PERL_SYNOP
Obtime ID LATITU LONGITU PSTA DIR SPD TEMPE DEW_T RH H_VIS WW CC PRED ENTRY_DATE CL CM CH PTND PTND_CODE WW1 CLOUD_H
2010 01 01 00 00 89059 -63.32 -56.68 null 0 0 -.9 -6.8 null 81 null 5 994.1 06-JAN-10 1 1 0 .1 4 null 1000
2010 01 01 12 00 89059 -63.32 -56.68 null 80 2 -1.7 -7.1 null 82 null 4 993.1 06-JAN-10 4 0 0 .2 4 null 600
2010 01 01 15 00 89059 -63.32 -56.68 null 230 6 -1.1 -7.1 null 82 null 5 992.7 06-JAN-10 1 0 0 .4 7 null 1500
2010 01 01 18 00 89059 -63.32 -56.68 null 260 6 .1 -5.2 null 82 null 2 992.7 06-JAN-10 0 1 0 0 4 null 2500
2010 01 01 21 00 89059 -63.32 -56.68 null 250 10 1.7 -.5 null 82 null 5 992.6 06-JAN-10 0 1 0 .1 7 null 1000
i have try with the coding in my program like this :
[yy,mm,dd,Hr,m,ID,LAT,LONG,PSTA,DIR,SPD,TEM,DEW_T,RH,H_VIS,WW,CC,PRED,DD,MM,YY,CL,CM,CH,PTND,PTND_CODE,WW1,CLOUD_H]...
= textread('010110.txt','%4d%2d%2d%2d%2d%s%4.4f%4.4f%d%4d%4d%4.4f%4.4f%d%4.4f%d%4d%4.4f%2d-%2d-%2d%d%d%d%f%d%d%4d','delimiter',',','headerlines',2,'whitespace','\n', 'emptyvalue',NaN);
when i run this code, it is not successful read the data. can you tell me whats wrong in my code. i attach my file.
Thank you very much for you answer my question

Best Answer

Comments
  • The Mathworks recommend textscan over the older textread
  • The delimiter in your file is space, char(32)
  • Matlab does not do "fixed format reading". Thus, the detailed specifiers do not help.
  • I find it easier to read dates, e.g. "06-JAN-10", as strings and parse in a second step. The format string is tricky to get right as is.
Try
fid = fopen( 'cssm.txt', 'r' );
cac = textscan( fid ...
, '%d%d%d%d%d%d%f%f%s%d%d%f%f%s%d%s%d%f%s%d%d%d%f%d%s%d' ...
, 'Delimiter' , ' ' ...
, 'Headerlines' , 2 );
fclose( fid );
cac
where cssm.txt is a text file with your data - copy&paste. It returns
cac =
Columns 1 through 6
[5x1 int32] [5x1 int32] [5x1 int32] [5x1 int32] [5x1 int32] [5x1 int32]
Columns 7 through 12
[5x1 double] [5x1 double] {5x1 cell} [5x1 int32] [5x1 int32] [5x1 double]
Columns 13 through 18
[5x1 double] {5x1 cell} [5x1 int32] {5x1 cell} [5x1 int32] [5x1 double]
Columns 19 through 24
{5x1 cell} [5x1 int32] [5x1 int32] [5x1 int32] [5x1 double] [5x1 int32]
Columns 25 through 26
{5x1 cell} [5x1 int32]
and
>> cac{19}
ans =
'06-JAN-10'
'06-JAN-10'
'06-JAN-10'
'06-JAN-10'
'06-JAN-10'