Convert double to cell array
29 次查看(过去 30 天)
显示 更早的评论
I've read some data from a text file using textscan and managed to create a 1x6 cell array, the first column of which includes a time stamp, though not in the format I require. Example:
1643201283507717200
The translation of this is 16:43:20.128... to 13 decimal points.
Can anyone advise on how I might convert this to an actual time stamp, ideally HH:MM:SS without losing any of the precision, and applying this to every value in the column. For reference, Ill be looking to calculate the time delta from the first value
Thank you
0 个评论
采纳的回答
Cris LaPierre
2022-1-28
编辑:Cris LaPierre
2022-1-28
You are going to run into some precision errors with a number that large.
format long
t = 1643201283507717200;
t-1643201283507717000 % result should be 200
I think it would be best to go back to the original textscan operation and implement changes there to capture this as separate HH, mm, ss, and ms.
t = '1643201283507717200';
T = textscan(t,'%2f %2f %2f %f')
T{4} - 1283507717199 % result should be 1
You will still have the challenge of capturing milliseconds accurately to 13 decimal places, but at least here all the numbers are still correct.
You could then build up a time vector. However, you are again limited to just 9 decimal places, and you will again not have 13 decimal places of precision. This has to do with how floating point numbers are stored digitally.
tm = duration(T{:,1},T{:,2},T{:,3},T{:,4}*1e-10,'Format','hh:mm:ss.SSSSSSSSS')
milliseconds(tm - duration(16,43,20,128.3507717000)) % answer should be 2e-8
I guess the first question, then, is is your timestamp format correct, and if so, is it truly accurate to that number of decimal places? If so, then datetimes or durations may not be the appropriate choice for you.
3 个评论
Cris LaPierre
2022-1-28
The problem with converting the entire timestamp to seconds is you end up making your number even larger. If it is just the that is important, I think I would do the following.
- Modify the original textscan to read in the time as hh, mm, ss, ms as shown previously.
- Convert the hh,mm,ss into a duration
- Subtract the first duration from all durations, and first ms from all ms.
- Find an approproate way to combine the duration with the ms (can add them if both are scaled correctly)
Please keep in mind this is a contrived example since you haven't shared your data. You are still dealing with some very small numbers
format long
t = '1643201283507717200 1643201283507717300';
T = textscan(t,'%2f %2f %2f %13f')
ms = T{:,4}
tm = duration(T{:,1:3},'Format','hh:mm:ss')
dtm = milliseconds(tm-tm(1))
dms = ms-ms(1)
dt = dtm + milliseconds(dms*1e-10)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!