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

조회 수: 5 (최근 30일)
Elisa
Elisa 2024년 10월 9일
편집: Walter Roberson 2024년 10월 18일
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

답변 (4개)

Zinea
Zinea 2024년 10월 9일
편집: Zinea 2024년 10월 9일
Hi @Elisa,
The error above occurs due to the attempt to use a datetime object as an index, which is not allowed. The issue arises from the month function call when it tries to process the Date variable. To resolve this, the following changes need to be made:
  1. Remove unnecesary string conversion by directly passing raw.textdata to datetime:
Date = datetime(raw.textdata(2:end, 1), 'InputFormat', 'dd-MMM-yy');
2. Use datestr to directly format the date into 'MMM yy':
m_Labels(i) = datestr(m_Date, 'mmm yy'); % Create the 'MMM yy' label
Given below is the output after the above corrections:
  댓글 수: 2
Elisa
Elisa 2024년 10월 9일
but it is suggested to not use the in-built function datestr
Stephen23
Stephen23 2024년 10월 9일
"Use datestr..."
DATESTR is deprecated, as its documentation makes very clear:
It is superfluous anyway, the datetime will get automagically converted when allocated to the string array:
str = "";
str(1) = datetime('now', 'Format','MMM yy')
str = "Oct 24"

댓글을 달려면 로그인하십시오.


Stephen23
Stephen23 2024년 10월 9일
편집: Stephen23 2024년 10월 9일
s = ""; % your string array
dt = datetime('now')
dt = datetime
09-Oct-2024 13:00:01
dt.Format = 'MMM yy'; % the format given in your example code
s(1) = dt
s = "Oct 24"
dt.Format = 'yyyyMM'; % the format given in your title
s(1) = dt
s = "202410"
If you want to avoid implicit type conversion:
s(1) = compose("%u%02u",dt.Year,dt.Month)
s = "202410"

Steven Lord
Steven Lord 2024년 10월 9일
I would rename the variable you've created called month, as it will prevent you from calling the month function while it exists (or at all in a function, if you define the variable inside that function.)
dt = datetime("today")
dt = datetime
09-Oct-2024
callMonthFunction = month(dt) % 10
callMonthFunction = 10
month = 42 % define month variable
month = 42
y = month(dt) % error, not 10, as you can't index into the variable with today.
Unable to use a value of type datetime as an index.

month appears to be both a function and a variable. If this is unintentional, use 'clear month' to remove the variable 'month' from the workspace.

Seth Furman
Seth Furman 2024년 10월 18일
The string function takes a format argument. We can specify adjacent year and month in the format with "uuuuMM".
string(datetime(2024,4,1), "uuuuMM")
ans = "202404"

카테고리

Help CenterFile Exchange에서 Calendar에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by