Find the Monday preceding the third Friday of the month
Show older comments
Ok, I have data spanning numerous years, and part of my analysis requires me to know the Monday that precedes the third Friday of every month. Right now I am stuck on just calculating the third Friday of the month.
tdayStr=datestr(datenum(num2str(vifDate),'yyyymmdd')); % turn vifDate into string
dt=datetime(tdayStr); % get datetime format to extrapolate day of week
m=month(dt); % get month of each date
y=year(dt); % get year of each date
dayNumber=day(dt,'dayofweek'); % Friday=6
x=zeros(81,1); % preallocate a vector and find the Fridays of each month/year
yUnique=unique(y);
mUnique=unique(m);
for i = yUnique(1:end);
for j = mUnique(1,end);
f=find(j==mUnique & dayNumber==6);
%x(i)=f(3);
end
end
The code breaks down at "f=find(j==mUnique & dayNumber==6);", and the error says inputs must have the same size. How can I troubleshoot this error, and more importantly, after finding the third Friday of every month, how can I get the preceding Monday?
Thank you for reading.
Accepted Answer
More Answers (1)
Peter Perkins
on 13 Jul 2015
In R2014b or later, using datetime, this is simple:
% Generate some random dates
>> d = sort(datetime('now','Format','eee, dd-MMM-yyyy') + caldays(randi(300,5,1)))
d =
Thu, 03-Sep-2015
Sun, 08-Nov-2015
Tue, 26-Jan-2016
Sun, 21-Feb-2016
Fri, 26-Feb-2016
% Get the first of the month
>> d1 = dateshift(d,'start','month')
d1 =
Tue, 01-Sep-2015
Sun, 01-Nov-2015
Fri, 01-Jan-2016
Mon, 01-Feb-2016
Mon, 01-Feb-2016
% Get the 3rd Friday
>> d2 = dateshift(d1,'dayofweek','friday',3)
d2 =
Fri, 18-Sep-2015
Fri, 20-Nov-2015
Fri, 15-Jan-2016
Fri, 19-Feb-2016
Fri, 19-Feb-2016
% Get the previous Monday
>> d3 = d2 - caldays(4)
d3 =
Mon, 14-Sep-2015
Mon, 16-Nov-2015
Mon, 11-Jan-2016
Mon, 15-Feb-2016
Mon, 15-Feb-2016
I'm not 100% sure what your vifDate variable contains, but it looks like it's "packed decimal" values. Try this to turn them into datetimes:
>> datetime(20150713,'ConvertFrom','yyyymmdd')
ans =
13-Jul-2015 00:00:00
Hope this helps.
Categories
Find more on Time Series Objects in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!