# Calculating number of monthly events

7 views (last 30 days)
davit petraasya on 25 Jan 2016
Answered: BhaTTa on 25 Jul 2024 at 3:40
Hi
I have events time series. (see attached) How I can calculate monthly number of events.

BhaTTa on 25 Jul 2024 at 3:40
To calculate the monthly number of events from your provided date data in the tableformonthly.xlsx file in MATLAB. Here's a step-by-step guide to achieve this:
1. Read the data from the Excel file.
2. Convert the dates to a MATLAB datetime format.
3. Group the dates by month and count the number of events per month.
Here is the MATLAB code to accomplish this:
% Read the data from the Excel file
filename = 'tableformonthly.xlsx';
% Convert the dates to datetime format
dates = datetime(data.Var1, 'InputFormat', 'dd-MM-yyyy');
% Extract the year and month from the dates
years = year(dates);
months = month(dates);
% Combine year and month into a single variable
yearMonth = datetime(years, months, ones(size(months)));
% Count the number of events per month
[uniqueMonths, ~, idx] = unique(yearMonth);
eventCounts = accumarray(idx, 1);
% Display the results
monthlyEventsTable = table(uniqueMonths, eventCounts, 'VariableNames', {'Month', 'EventCount'});
disp(monthlyEventsTable);
Explanation
1. Reading the Data: The readtable function reads the data from the Excel file into a table.
2. Converting Dates: The datetime function converts the date strings to MATLAB's datetime format.
3. Extracting Year and Month: The year and month functions extract the year and month from the datetime array.
4. Combining Year and Month: Create a new datetime array representing the first day of each month.
5. Counting Events: The unique function finds unique month-year combinations, and accumarray counts the occurrences of each unique month.
6. Displaying Results: The results are displayed in a table showing each month and the corresponding event count.