Determination of Event set from matrix
1 view (last 30 days)
Show older comments
Hello
I have a matrix set as below
2024 8 1 5
2024 8 2 2
2024 8 3 5
2024 8 4 5
2024 8 5 2
2024 8 6 3
2024 8 7 5
2024 8 8 5
2024 8 9 4
2024 8 10 3
2024 8 11 5
2024 8 12 5
The first three columns show year, month and day & the last column show index for event set. If the last column is 5, then it would be qualified as one event. If the last column is 2 in between, for example, for 1/8/2024 to 4/8/2024, both these events are considered as part of the same event with event duration 4 days. However, 5/8/2024, is not followed by 5, so they are not the part of event that ended on 4/8/2024. Please suggest how I can join these two events and determine event duration if they are sandwitched by a small event with event index 2.
0 Comments
Accepted Answer
Jatin
on 21 Sep 2024
Edited: Jatin
on 21 Sep 2024
From your explanation, I understand that if an event starts and ends with an index of 5, and there is a 2 sandwiched between two 5s, the entire sequence should be treated as a single event. However, if an event index of 2 is not followed by a 5, or if any index other than 2 or 5 appears, it breaks the event chain. and you want to determine the event duration for this logic.
This can be implemented in MATLAB using logical indexing, vectorized operations and tracking certain states, as shown in the following code:
data = [2024 8 1 5;
2024 8 2 2;
2024 8 3 5;
2024 8 4 5;
2024 8 5 2;
2024 8 6 3;
2024 8 7 5;
2024 8 8 5;
2024 8 9 4;
2024 8 10 3;
2024 8 11 5;
2024 8 12 5];
%4th column
event_type = data(:,4);
% Find indices where event starts and ends with 5
event_5_idx = find(event_type == 5);
% Initialize an array to store the event durations
event_durations = [];
start_idx = event_5_idx(1); % Set the first event start
for i = 2:length(event_5_idx)
% Check if the current index is consecutive or sandwiched by a 2
if all(event_type(event_5_idx(i-1)+1:event_5_idx(i)-1) == 2)
% It's part of the same event
continue;
else
% End the event and calculate the duration
event_end = event_5_idx(i-1);
duration = data(event_end, 3) - data(start_idx, 3) + 1;
event_durations = [event_durations; data(start_idx, 3), data(event_end, 3), duration];
% Start a new event
start_idx = event_5_idx(i);
end
end
%last event
event_end = event_5_idx(end);
duration = data(event_end, 3) - data(start_idx, 3) + 1;
event_durations = [event_durations; data(start_idx, 3), data(event_end, 3), duration];
% Display the event durations
disp('Event Start Day - Event End Day - Duration (Days)');
disp(event_durations);
I hope you find this helpful!
2 Comments
Jatin
on 21 Sep 2024
See if the updated answer using logical indexing and vectorized operations helps your cause.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!