How to get only duration calculated from datetime type variables as an integer/real scalar?
Show older comments
Hi,
I have some data from a sensor with date-time values and I need to compute something like below:
timeduration = max(datetimevalue) - min(datetimevalue);
rate = A/timeduration ;%A is a set of double values; sensor readings within the duration
where, max(datetimevalue) = 02-Dec-2016 15:30:26 and min(datetimevalue) = 02-Dec-2016 15:30:06
So I get timeduration as 00:00:20.
when I use rate = A/timeduration, it shows an error 'The denominator in matrix division for duration arrays must be a real scalar double value'.
What I want to do is, let matlab calculate the duration and take the duration as an integer (in the above case it is 20) and calculate the rate.
How do I do this? For an experiment or two, I can manually change it, but when I have many experiments to do, I would like to make matlab do it automatically so I do not have to hard-code it. (I have tried using etime, but no good).
Thanks in advance.
Accepted Answer
More Answers (2)
Geoff Hayes
on 6 Dec 2016
laksi11 - one way would be for you to convert your datetime values into serial numbers using datenum as
timeDurationSerial = datenum(max(datetimevalue)) - datenum(min(datetimevalue));
and then convert that duration into seconds as
timeDurationSec = timeDurationSerial*86400;
The timeDurationSerial is a serial number which represents the whole and fractional number of days from a fixed, preset date. So we convert this difference to seconds using 86400 (the number of seconds in a day). Your code could then be simply
timeDurationSerial = (datenum(max(datetimevalue)) - datenum(min(datetimevalue)))*86400;
The above should work...I can't test it out since R2014a doesn't have the datetime function.
2 Comments
Sean de Wolski
on 6 Dec 2016
I would not recommend this. Datetime has many features lacking from datenum, use the conversion functions like seconds, hours, etc. to get the double output.
lexi11
on 6 Dec 2016
Mohd Owais
on 15 Feb 2023
0 votes
% Usain Bolt's 100-meter dash record
distance = 100; % meters
time = 9.58; % seconds
hundred = (distance/time) * 3.6; % km/h
% Eliud Kipchoge's marathon record
distance = 42.195; % kilometers
time = hours(2) + minutes(1) + seconds(39); % convert to duration
marathon = (distance/time) * 3.6; % km/h
3 Comments
Mohd Owais
on 15 Feb 2023
The denominator in matrix division for duration arrays must be a real scalar double value.
Walter Roberson
on 15 Feb 2023
distance / hours(time)
Convert your second time variable into a number of hours using the hours function.
time = hours(2) + minutes(1) + seconds(39)
timeInHours = hours(time)
whos
Note that time is a duration array while timeInHours is a double value.
Categories
Find more on Dates and Time 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!