将 regexprep 与元胞数组结合使用以对冒号进行格式化

Use regexprep with cell array for colons to format

我的元胞数组格式如下:

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

我正在尝试将输出格式化为 4 列向量:

a = 23
    22
    12
    11

b = 34
    34
    34
    34

c = 22
    11
    08
    02

d = 959511
    885113
    995146
    383092

我正在使用regexprep对数据进行操作:

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

然而,这仅适用于数据集中的一个字符串,而不是所有字符串。

如何将字符串分成 4 个列向量 -- 使用 regexprep 作为冒号:并在下面显示输出?

如果您愿意使用正则表达式的其他解决方案:strplit 可以拆分为任何所需的字符:

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

当然,这仅在您的数据始终具有这种结构(两个冒号,然后是一个点)时才有效

这里有一个方法:

r = cell2mat(cellfun(@str2double, regexp(t, ':|\.', 'split'), 'uniformoutput', false));

这给了

r =
          23          34          22      959511
          22          34          11      885113
          12          34           8      995146
          11          34           2      383092

如果确实需要四个独立的变量,可以使用:

r = num2cell(r,1);
[a, b, c, d] = r{:};

我建议使用 split 而不是 strsplit。 split 将对向量进行操作,如果您使用字符串数据类型,则只需对字符串调用 double 即可获取数值

>> profFunc
Adriaan's Solution: 5.299892
Luis Mendo's Solution: 3.449811
My Solution: 0.094535

 function profFunc()

    n = 1e4; % Loop to get measurable timings

    t = ["23:34:22.959511";
         "22:34:11.885113";
         "12:34:08.995146";
         "11:34:02.383092"];

    tic
    for i = 1:n
        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
    end
    fprintf('Adriaan''s Solution: %f\n',toc);

    tic
    for i = 1:n
        r = cell2mat(cellfun(@str2double, regexp(t, ':|\.', 'split'), 'uniformoutput', false));
        r = num2cell(r,1);
       [a, b, c, d] = r{:};
    end
    fprintf('Luis Mendo''s Solution: %f\n',toc);

    tic
    for i = 1:n
        x = split(t,[":" "."]);
        x = double(x);

        a = x(:,1);
        b = x(:,2);
        c = x(:,3);
        d = x(:,4);
    end
    fprintf('My Solution: %f\n',toc);