Search code examples
stringmatlabcell-arrayregexp-replace

Use regexprep with cell array for colons to format


I have a cell array formatted as:

t = {'23:34:22.959511';
     '22:34:11.885113';
     '12:34:08.995146';
     '11:34:02.383092'}

I am trying to format the output as 4 column vectors as:

a = 23
    22
    12
    11

b = 34
    34
    34
    34

c = 22
    11
    08
    02

d = 959511
    885113
    995146
    383092

I am using regexprep to operate on the data:

a = regexprep(t,':34:22.959511', '')

However this only pertains to only one string in the data set and not all strings.

How do I divide the string into 4 column vectors -- using regexprep for colon: and display the output below?


Solution

  • If you're willing to use other solutions that regexp: strplit can split on any desired character:

    a = zeros(numel(t),1);
    b = zeros(numel(t),1);
    c = zeros(numel(t),1);
    d = zeros(numel(t),1);
    
    for ii = 1:numel(t)
        C = strsplit(t{ii}, ':');
        a(ii) = str2double(C{1});
        b(ii) = str2double(C{2});
        tmp = strsplit(C{3},'.'); % Additional split for dot
        c(ii) = str2double(tmp{1});
        d(ii) = str2double(tmp{2});
    end
    

    Of course this only works when your data always has this structure (two colons, then one dot)