How do I get matlab to recognize a date in a .txt file?
3 次查看(过去 30 天)
显示 更早的评论
I have a .txt file with two columns, the first with dates in the format yyyy-mm-dd and the second with prices such as '42.23'. However, when I load the .txt file into matlab it only recognizes the year.
load data.txt
>> data(1,1)
ans =
2005
or
>> data(1,:)
ans =
1.0e+03 *
2.0050 0.0422
I need matlab to see the entire date for plotting purposes. Does anyone know how I can fix this?
0 个评论
采纳的回答
Kirby Fears
2015-11-17
编辑:Kirby Fears
2015-11-17
Determine what the delimiter of your text file is. Space, tab, comma, etc. Then read the text file with one of the Matlab text reading functions.
Here is some example code tailored to your use case.
% delim = ' '; % space delimited
delim = '\t'; % tab delimited
% delim = ','; % comma delimited
fid = fopen('data.txt'); % open file
dataIn = textscan(fid,'%s %n','Delimiter',delim); % read file
fclose(fid); % close file
% dataIn{1} contains dates as char arrays
% dataIn{2} contains values as doubles
% convert to matlab date numbers
myDates = datenum(dataIn{1},'yyyy-mm-dd');
disp(datestr(myDates)); % Display datenumbers as strings
You can use date numbers for the x-axis of your plot.
plot(myDates,dataIn{2});
datetick;
Hope this helps.
0 个评论
更多回答(1 个)
Peter Perkins
2015-11-19
You may fnid that using readtable, and a format such as '%{yyyy-MM-dd}D%f', and perhaps specifying an appropriate delimiter, works for you.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Dates and Time 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!