expression to calculate the time difference using Matlab functions

조회 수: 4 (최근 30일)
Rob
Rob 2025년 6월 19일
답변: Rik 2025년 6월 19일
I have many pairs of times expressed, for example, as "3:19" and "1:28.4". I know I can break these up and multiplly by 60, etc, to get the time difference in seconds, but is there a Matlab function that does it?

채택된 답변

Rik
Rik 2025년 6월 19일
The closest to what you need is the duration function, but that has very limited support for text input.
str='3:19';
try,duration(str),catch ME,warning(ME.message),end
Warning: The duration text format is ambiguous. Specify 'InputFormat' with 'hh:mm' or 'mm:ss'.
str='1:28.4';
try,duration(str),catch ME,warning(ME.message),end
Warning: The duration text format is ambiguous. Specify 'InputFormat' with 'hh:mm' or 'mm:ss'.
You can also write something yourself:
delta=time2duration('3:19')-time2duration('1:28.4');
seconds(delta)
ans = 110.6000
function d=time2duration(str)
RE=['((\d+):)?',... % optional hours
'(\d?\d):',... % one or two digit minutes
'(\d?\d(\.\d+)?)']; % seconds (with optional decimals)
x=regexp(str,RE,'tokens');
t = str2double([x{:}]);
t(isnan(t))=0;
d=duration(t(1),t(2),t(3));
end

추가 답변 (0개)

카테고리

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

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by