How to find something that you're not looking for?!
1 view (last 30 days)
Show older comments
Hey everyone!
So I haven written a couple matlab codes to predict the future values of some time series. Within those codes i need the following command:
start=datenum(2011,01,01,0,0,0);
finish=datenum(2011,31,12,23,0,0);
a=find(date==start);
b=find(date==finish);
The vector "date" contains dates and I want to find the exact position of the dates that I have assigned to the variables start and finish. However depending on the data I am using, sometimes there are some gaps within the dates in vector "date". For example vector "date" contains all dates from 01-01-2009 until 12-31-2013 but the dates from 12-28-2011 to 01-05-2012 are missing. Consequently if I ran this code, I would get the index of my start date (assigned to variable a) but the index of my finish date (assigned to variable b) is empty.
Is there any way to determine the closest match to the date I am looking for? For example in this case I would want matlab to tell me the exact position of the date 12-28-2011 within the vector "date" if it cannot tell me the position the the date "finish".
I would be grateful for any ideas how to work around this. Restructuring the vector "date" and filling it with the missing dates is no solution for me at the moment...
Thank you so much!!
0 Comments
Accepted Answer
Guillaume
on 22 Oct 2014
How about:
[~, idx] = min(abs(date - finish));
3 Comments
Guillaume
on 23 Oct 2014
The above just give you one value, idx which is the index of the closest date to finish (aka the index of the minimum absolute difference between date and finish).
I'm not sure what you did, but it wasn't what I wrote:
mydates = [datenum([2009 1 1]):datenum([2011 12 27]) datenum([2012 1 6]):datenum([2013 12 31])];
start = datenum([2011 1 1]);
finish = datenum([2011 12 31]);
[~, a] = min(abs(mydates - start));
[~, b] = min(abs(mydates - finish));
[a b]
returns
ans = [731 1091]
datestr(mydates([a b]))
returns
ans =
01-Jan-2011
27-Dec-2011
By the way, don't call your variable date since it shadows the name of a matlab built-in function.
More Answers (1)
per isakson
on 22 Oct 2014
Edited: per isakson
on 22 Oct 2014
Try this
ix = find( date >= finish, 1, 'first' );
2 Comments
Guillaume
on 23 Oct 2014
My answer will give you the closest date regardless if it's before or after.
See Also
Categories
Find more on Time Series Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!