我有一个格式为:
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
作为冒号:并显示下面的输出?
如果您愿意使用regexp的其他解决方案: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);