Is there a more efficient way to read a .txt data file into MATLAB?
古いコメントを表示
I have this .txt data file
Date Tmin°C Tmax°C rain cm snow cm
1950-01-01 -22.100 -3.300 0.000000 0.020000
1950-01-02 -18.800 -1.600 0.000000 0.050000
...
I want to read it and save it in a var (structure or cell)to use the information in my programme. I need to keep date for ref and header to make this file more easy to other user.
How to do that efficiently?
EDIT: Follow up (should have been a separate question...)
I always need to find monthly mean of each years
I use the same .txt data file of the previous question results shoud be like this ex:
Jan 1950 = -20
Jan 1951 = -22
Feb 1950 = -24
Feb 1951 = -23
In a structure or cell or one var for each mounth
The code I did to do that is very primitive, and the 29 feb is complicated to deal so my code is slow, heavy.
採用された回答
その他の回答 (4 件)
R. Scott
2011 年 2 月 18 日
2 投票
If you have the stats toolbox then look at using a 'dataset' you could even import your .txt file directly into a dataset.
R. Scott
2011 年 2 月 18 日
1 投票
Have you looked at the fun 'textscan'
fid = fopen('fileToRead')
data = textscan(fid, ' delimiters here %s%d...', 'delimiter', ',', 'headerlines',0)
fclose(fid)
play around with textscan or enter textscantool in the command window.
Matt Tearle
2011 年 2 月 18 日
BTW, Jonathan, a good practice is to ask a separate new question, because this second question might be something someone else might be looking for.
Anyway, have a look at the various date conversion functions datenum, datestr, and datevec. At the moment you have a cell array of date strings. To manipulate dates in terms of days/months/years, it's probably easiest to convert to date vectors using datevec. This will give you a matrix, one row for each date; the columns being the years, months, and days. Something like this, then, would enable you to do monthly analysis:
dates = data{1}; % dates is a cell array of date strings
mintemp = data{2}; % mintemp is double array
dtvc = datevec(dates);
yrs = dtvc(:,1);
mths = dtvc(:,2);
for k = 1:12
idx = (yrs==1950) & (mths==k); % logical index
mintemps_thismonth = mintemp(idx); % extract data for this month
disp(['Avg min temp for ',datestr([1950,k,1,0,0,0],'mmmm yyyy'),...
' is ',num2str(mean(mintemps_thismonth))])
end
Walter Roberson
2011 年 2 月 18 日
1 投票
カテゴリ
ヘルプ センター および File Exchange で MATLAB についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!