sum multiple clock times

조회 수: 13 (최근 30일)
SNM Nima
SNM Nima 2023년 1월 14일
답변: Raghav 2023년 2월 13일
Hi
How to sum multiple clock times in MATLAB assuming it resets every 24 hours?
  댓글 수: 1
the cyclist
the cyclist 2023년 1월 14일
Please read this guide about how to ask a good question, and edit your question to improve it.
Specifically, it would be useful to know data type your times are stored as. It would be most helpful if you uploaded your input data.

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

채택된 답변

Raghav
Raghav 2023년 2월 13일
Hi,
I understand that you want to sum multiple clock times.
In the following solution, I have assumed that the input argument times is a cell array of time strings in the format hh:mm:ss & the function returns the sum of all times as a time string in the same format.
To sum multiple clock time in MATLAB assuming they reset every 24 hours, you can perform the following steps:
  1. Convert each time string to a numerical value in hours.
  2. If the resulting value is greater than 24, subtract 24 to ensure that it is within the range of [0, 24).
  3. Add the numerical values of all times.
  4. If the sum is greater than 24, subtract 24 to ensure that it is within the range of [0, 24).
  5. Convert the resulting numerical value back to a time string.
You may refer to the below mentioned example code for summing multiple clock times in MATLAB:
function total_time = sum_clock_times(times)
% Initialize the total time
total_time = 0;
% Loop through each time string
for i = 1:length(times)
% Split the time string into hours, minutes, and seconds
[hours, minutes, seconds] = strread(times{i},'%d:%d:%d');
% Convert the time to a numerical value in hours
time_in_hours = hours + minutes/60 + seconds/3600;
% If the time is greater than 24, subtract 24
if time_in_hours >= 24
time_in_hours = time_in_hours - 24;
end
% Add the time to the total time
total_time = total_time + time_in_hours;
end
% If the total time is greater than 24, subtract 24
if total_time >= 24
total_time = total_time - 24;
end
% Convert the total time to a time string
hours = floor(total_time);
minutes = floor((total_time - hours) * 60);
seconds = floor((((total_time - hours) * 60) - minutes) * 60);
total_time = sprintf('%02d:%02d:%02d', hours, minutes, seconds);
end
Moreover, you may also have a look at the similar question thread from the following link: https://in.mathworks.com/matlabcentral/answers/694005-summing-datenum-resets-after-24-hours
Regards,
Raghav Bansal

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Clocks and Timers에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by