MATLAB: Find the Monday preceding the third Friday of the month

date indexingMATLAB

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.

Best Answer

If you have the Financial Toolbox, you can do this with nweekdate which will do both aspects, finding third Friday, and finding the Monday in the same week as the third Friday.
More
Without Financial Tbx, this can be done with some grouping. Here is an example for 2015:
% 2015
Time = (datetime(2015,1,1):days(1):datetime(2015,12,31)).';
% Day of Month and whether it's a Friday
mt = month(Time);
idxFriday = strcmp(day(Time,'shortname'),'Fri');
% One to number of days
oneToN = (1:numel(Time))';
% Group Fridays by month
Fridays = accumarray(mt(idxFriday),oneToN(idxFriday),[],@(x){sort(x)});
% Keep third index and subtract four days for Monday
idxMonday = cellfun(@(x)x(3),Fridays)-4;
% Extract from Time
Time(idxTime)
Yields:
12-Jan-2015
16-Feb-2015
16-Mar-2015
13-Apr-2015
11-May-2015
15-Jun-2015
13-Jul-2015
17-Aug-2015
14-Sep-2015
12-Oct-2015
16-Nov-2015
14-Dec-2015