Take string input and reformat as cell array
Show older comments
I would like to convert a string into a cell array. Here is a small example of string:
[{"ts": "2018-07-03T06:30:07", "v": 1.0}, {"ts": "2018-07-03T06:30:12", "v": 0.0}, {"ts": "2018-07-03T08:41:06", "v": 1.0}]
I would like to convert this into the following format:
[ datetime ] [number]
The ts and v refer to timestamp and value, and are not important to keep.
I believe using the textscan is an efficient way to do it, however I cannot figure out how to use it properly, any help is appreciated!
2 Comments
Stephen23
on 10 Jun 2020
@Connor Brackley: please upload a sample of your data by clicking the paperclip button.
Connor Brackley
on 10 Jun 2020
Accepted Answer
More Answers (1)
Ameer Hamza
on 10 Jun 2020
Edited: Ameer Hamza
on 10 Jun 2020
Try this
str = fileread('test.txt');
dts = regexp(str, '"ts": "([0-9:T-]*)"', 'tokens');
vs = regexp(str, '"v": ([0-9.]*)', 'tokens');
dts = cellfun(@(x) datetime(x, 'InputFormat', 'yyyy-MM-dd''T''HH:mm:ss'), [dts{:}]);
vs = cellfun(@str2double, [vs{:}]);
T = table(dts.', vs.', 'VariableNames', {'DateTime', 'V'});
disp(T)
Result
DateTime V
____________________ _
03-Jul-2018 06:30:07 1
03-Jul-2018 06:30:12 0
03-Jul-2018 08:41:06 1
1 Comment
Connor Brackley
on 10 Jun 2020
Categories
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!