Chandler Cree
Chandler Cree

Reputation: 111

Convert String to Array of Specific Format

I have a string of format

"'Year'-'Month'-'Day'T'Hour':'Minute':'Second'Z" for example '2020-11-26T16:56:09.676Z'

(Note the milliseconds are considered part of the second)

I would like to convert it to the format:

t1 = 1x6

2020 11 26 16 56 09.676

Or in other words a 1x6 array.

Note: This is to be completed using MatLab.

Upvotes: 0

Views: 103

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112769

You can

  1. Use regexp with the 'match' input flag to detect the numbers as one or more digits (\d+) optionally followed by a decimal point (\.?) and then zero or more digits (\d*). This will give a cell array of strings.
  2. Apply str2double to convert the strings to numbers. This will give a numeric row vector.

s = '2020-11-26T16:56:09.676Z';
result = str2double(regexp(s, '\d+\.?\d*', 'match'));

Upvotes: 1

Related Questions