Have a string with an analog time value, how to convert it to total time elapsed?

3 visualizaciones (últimos 30 días)
Hello, I have a worksheet with time data as strings in seperate rows in a single columns. I just copied 2 entries so you can see what the data looks like:
"00:00:00,002"
"00:00:00,003"
I would like the above strings to be turned into any other data type that I can plot on the x-axis of my graph (double, int, anything!!). If I use a function like string2double it just tells me that all these values are not numbers, which makes sense. I have tried to use a function which considers the ':' as delimiters after which I could just convert the seperate colums to doubles but this throws an error at me saying that my input should be a string scalar.
Is there any way to convert this data?

Respuestas (1)

Eric Sofen
Eric Sofen el 20 de Mzo. de 2018
The duration datatype is the correct type to represent this data, and you can plot durations.
In R2018a, there is a new capability to parse durations from text. It is limited to timer formats (e.g. hh:mm:ss) and right now doesn't support a comma as a decimal separator. However, if your data is coming from text, you can use ImportOptions to specify the decimal separator. Something like
opts = detectImportOptions(fi);
% if the first variable is your time data as strings
opts = setvartype(opts,1,'duration');
opts = setvaropts(opts,1,'DecimalSeparator',',')
t = readtable(fi, opts);
plot(t.Var1,t.Var2)
If you're using an earlier release, the best bet is to use datetime text parsing and then peel off the time-of-day part. This works unless you have durations that are longer than 24 hours.
d = timeofday(datetime("00:00:00,002",'InputFormat','HH:mm:ss,SSS'))
% show sub-second precision
d.Format = 'hh:mm:ss.SSS'

Community Treasure Hunt

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

Start Hunting!

Translated by