Extract a portion of character

1 visualizzazione (ultimi 30 giorni)
NUR DALILA
NUR DALILA il 16 Dic 2022
Risposto: Walter Roberson il 17 Dic 2022
Hi... I've got a set of characters that I need to extract, convert to numbers, and perform a task on to find the differences between them. Here is an example of data:
'12/04/2022 15:22:52.211.674'
'12/04/2022 15:22:52.211.752'
'12/04/2022 15:22:52.211.830'
'12/04/2022 15:22:52.211.908'
I just need the last 6 numbers, such as below:
211.674
211.752
211.830
211.908
Next, I need to find the difference between the numbers, for example:
211.752 - 211.674
211.830 - 211.752
211.908 - 211.830
and store it in the new column.
Thank you:)

Risposte (1)

Walter Roberson
Walter Roberson il 17 Dic 2022
It would be possible to strip those values down to the milliseconds and nanoseconds as a simple text operation. However I did not do that here, because it is not robust: you need to assume that you might cross a boundary at some point. The code here uses the full precision of the inputs -- in theory it can even handle historic leap seconds.
format long g
D = {
'12/04/2022 15:22:52.211.674'
'12/04/2022 15:22:52.211.752'
'12/04/2022 15:22:52.211.830'
'12/04/2022 15:22:52.211.908'
};
D2 = regexprep(D, '\.(\d\d\d)$', '$1'); %fraction of seconds must be adjacent
D3 = datetime(D2, 'InputFormat', "MM/dd/yyyy HH:mm:ss.SSSSSS", 'Format',"MM/dd/yyyy HH:mm:ss.SSSSSS" )
D3 = 4×1 datetime array
12/04/2022 15:22:52.211674 12/04/2022 15:22:52.211752 12/04/2022 15:22:52.211830 12/04/2022 15:22:52.211908
[~, ~, S] = hms(D3) %if you really want to see the seconds
S = 4×1
52.211674 52.211752 52.21183 52.211908
%but do not look at just the seconds for the calculation, as you might have
%crossed a second boundary
nanodiff = seconds(diff(D3)) * 1e6 %nanoseconds
nanodiff = 3×1
78.000000000003 77.9999999999745 78.0000000000314

Community Treasure Hunt

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

Start Hunting!

Translated by