How to read a.txt file in matlab
显示 更早的评论
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
2 个评论
Innosens
2014-3-18
采纳的回答
更多回答(3 个)
Francesco
2014-3-18
0 个投票
I have always used textread and it works perfectly. A problem might arise when the value is null: I don't think MatLab can read it as a decimal or float: if not you can try so substitute the string null with NaN but I am not sure.
It is difficult to understand from your question because it is messy: please use the 'code' tool or use a smaller matrix just as example because in this way it is unreadable. Also I think that the type of error you get would be useful.
Joseph Cheng
2014-3-18
编辑:Joseph Cheng
2014-3-18
0 个投票
As you have consistent text file, perhaps writing your own function to parse out the data would be the way to go. using fgetl() and strfind() you can find the deliminators and parse out the data. where you can use str2double() wherever you need to convert to a double and keep things as strings where needed. Additionally you may want to set these as cells if the null values switch between number and string, or vary by length.
~J
David Sanchez
2014-3-18
You can try something like this:
fid = fopen('your_file.txt');
C = textscan(fid,'%s', 'CommentStyle','#');
fclose(fid);
headers = C{1,1}(1:22); % Obtime ID LATITU LONGITU PSTA DIR SPD TE...
lines = cell(26,5); % your data
for k=1:5
lines(:,k) = C{1,1}((23+26*(k-1)):(22+26*k));
end
You'll end up with a cell array, lines, with the information of your file in string format. Adapt it to your needs.
类别
在 帮助中心 和 File Exchange 中查找有关 Data Import and Export 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!