MATLAB: How do a get a specific day of the year

day of the year

This is my code:
for x = 1:n % adjust code for n>1
a = 1;
x;
%Load irradiation data
fid = fopen([source_data, '\csv_irrad\', d(x).name]); % open to wind data file
pause(5)
fmt ='%{dd/MM/yyyy}D %{HH:mm}D %f';
DATA = textscan(fid, fmt,'Delimiter', ',','HeaderLines',1);
[date time irrad] = DATA{1,1:3};
[year month day] = ymd(date);
SpecificDate = datetime(2016, 8, 1);
locate = ismember(date, SpecificDate);
irradiation = irrad(locate);%irradiation is data set used to calculate power output
end
I want to get the day of the year ( 1 to 365) when using this Specific Date code so I can input DAY later in the code. I have tried this D = day( datetime('08-Aug-2016', 'InputFormat', 'dd-MMM-yyyy' ), 'dayofyear' ) but get the error message – Function 'subsindex' is not defined for values of class 'datetime'.

Best Answer

The problem is caused by this line:
[year month day] = ymd(date);
When you have variables named year, month, and day, then you can no longer use the MATLAB functions of the same names. This is known as shadowing the function. So when you call day(datetime(...)), you are telling MATLAB that you want to index into your variable day using a datetime object, which does not make much sense and so MATLAB throws an error.
Solution: change the names of those variables, and clear your workspace (or restart MATLAB).
In future, always check if a name is used, before using it for any variable, e.g.:
which day -all