Info

This question is closed. Reopen it to edit or answer.

trying to extract the months to create a format looks like 202404, how to do that ?

1 view (last 30 days)
Date=datetime(raw.textdata(2:end,1),'InputFormat','dd-MMM-yy');%convert the data to date time
yr = year(Date); % Extract the year
mnth = month(Date); % Extract the month
% Create an array for the year-month combinations
yr_Month = yr * 100 + mnth;%example 202004
% Get unique year-month combinations
u_Months = unique(yr_Month);
%create month label in 'MMM yy" format
m_Labels = strings(length(u_Months), 1);
% Initialize vectors for monthly sums
m_sum_Production = zeros(length(u_Months), 1);
m_sum_T_Consumption = zeros(length(u_Months), 1);
m_sum_O_Consumption = zeros(length(u_Months), 1);
% Calculate the sum for each unique month-year combination
for i = 1:length(u_Months)
cur_Month = yr_Month == u_Months(i); % Logical index for the current month-year combination
m_sum_Production(i) = sum(Production(cur_Month)); % Monthly sum of Production
m_sum_T_Consumption(i) = sum(T_Consumption(cur_Month)); % Monthly sum of Total Consumption
m_sum_O_Consumption(i) = sum(O_Consumption(cur_Month)); % Monthly sum of Own Consumption
% Generate the corresponding 'MMM yy' label
yr_Part = floor(u_Months(i) / 100); % Extract the year
m_Part = mod(u_Months(i), 100); % Extract the month
% Create a datetime object for the first day of the month
m_Date = datetime(yr_Part, m_Part, 1);
% Format month as 'MMM yy'
m_Labels(i) = datetime(m_Date, 'mmm yy'); % Create the 'MMM yy' label
end
code is above
Unable to use a value of type datetime as an index.
Error in Q3 (line 15)
mnth = month(Date); % Extract the month
error is above

Answers (0)

This question is closed.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!