Hi @Jonathan Pelletier-Marcotte, from my understanding, you have generated the “tres” array that stores the status codes for each minute of the day, based on when each status is active. You have built the “Time_Ref,” “Time_on,” and “Time_off” arrays, which serve as input to the for loop. Now, you want to optimize the code further to get the same result.
To do this, we can convert “Time_on” and “Time_off” to datetime objects once to avoid repeated conversions inside the loop. Next, we can pre-allocate the “tres” array with empty arrays, which improves the performance. Finally, we can use logical indexing inside the for loop to avoid nested loops that improves the performance further.
Below is the updated MATLAB code with the described changes:
Date = datetime(2018, 11, 08);
Time_Ref = Date + minutes(1):minutes(1):Date + days(1);
tres = cell(length(Time_Ref), 1);
% Convert Time_on and Time_off to datetime arrays
Time_on = datetime({'2018-11-08 00:00:00'; '2018-11-08 00:00:00'; '2018-11-08 00:00:00'; '2018-11-08 00:46:29'; ...
'2018-11-08 03:51:33'; '2018-11-08 08:23:40'; '2018-11-08 23:51:37'});
Time_off = datetime({'2018-11-09 00:00:00'; '2018-11-09 00:00:00'; '2018-11-09 00:00:00'; '2018-11-08 12:46:41'; ...
'2018-11-08 03:52:44'; '2018-11-08 08:23:50'; '2018-11-08 23:51:47'});
Status = [850; 3030; 6042; 6052; 7018; 6052; 6052];
tic
for j = 1:length(Time_Ref)
% Find indices where the condition is met
indices = Time_off > Time_Ref(j) - seconds(59) & Time_on < Time_Ref(j);
% Collect statuses for those indices
tres{j} = Status(indices)';
end
toc
Attaching the documentation for logical indexing in MATLAB for reference:
I hope this helps.