Can one extract a unit of time from a duration object?
10 views (last 30 days)
Show older comments
Alexandre Aksenov on 1 Nov 2022
Edited: Alexandre Aksenov on 26 Dec 2022
Some of my programs of data analysis produce 'duration' objects, and I am looking for a way of printing them as strings.
I have the option of guessing an appropriate unit of time from data, then calling a (relatively unnatural) instruction like:
Relatively unexpectedly, both "char" and "string" operators' results seem to depend on how the object has been initially created, as the following code shows.
Tsec = seconds(1)
% 1 sec
Tmin = minutes(1)
% "1 min"
% "60 sec"
It is certainly possible to parse the output of "string", then to extract the unit of time, but I would like to find a simpler way of finding it. Getting identical results for equal durations would obviously be a positive point.
My question is related to this one:
Thanks for your attention!
Steven Lord on 1 Nov 2022
MATLAB will try to select a good format for the duration object based on the data with which it was created. But if you want all your duration objects to have a consistent format, you can specify it.
s = seconds(60)
formatForSeconds = s.Format
m = minutes(1)
formatForMinutes = m.Format
Let's change the format for m to be the same as the format for s.
m.Format = formatForSeconds
Now that they're using the same format, converting them to text data will give the same text data.
sString = string(s)
mString = string(m)
See the section about the Format property of duration objects on the duration documentation page for a list of available format components.
More Answers (1)
Lei Hou on 18 Nov 2022
Applying seconds/minutes/... to a duration array returns numeric value
>> d1 = seconds(60)
>> d2 = minutes(1)
>> x1 = seconds(d1)
>> x2 = seconds(d2)
Hoping this is helpful.
Find more on Data Type Conversion 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!