要快速完成此操作,请不要使用cellfun
or str2double
。一些可能性:
strjoin
with sscanf
Use strjoin组合元胞数组中的字符串x
成一个以空格分隔的长字符串,然后可以使用以下命令非常快速地对其进行解析sscanf
:
sscanf(strjoin(reshape(x,1,[])),'%f')
请注意reshape
包含在内是为了保证元胞数组是一行,按照以下要求strjoin
。一个简单的排列(.'
)如果你知道的话可以使用x
是一列,或者什么也没有,如果x
已经是一排了。
vertcat
(or str2mat
) with sscanf
代替strjoin
,形成虚逗号分隔的列表的字符串与x{:}
并将它们垂直连接起来vertcat(如果每个字符串具有相同数量的字符)。转置这个二维字符数组并sscanf
可以再次快速解析它:
sscanf(vertcat(x{:})','%f');
或者,如果每个字符串的字符数不同,您可以使用str2mat
,它创建一个空格填充的二维字符数组sscanf
还高兴地读到:
sscanf(str2mat(x)','%f');
test
创建一个包含 10,000 个随机数的字符串表示形式的元胞数组:
>> x = sprintfc('%f',rand(1e4,1));
注意未记录的使用sprintfc
打印到单元格。
参考方法:
>> tic; d0 = str2double(x); toc
Elapsed time is 0.302148 seconds.
>> tic; d1 = cellfun(@(x) sscanf(x,'%f'),x); toc
Elapsed time is 0.277386 seconds.
>> isequal(d0,d1)
ans =
1
strjoin
and vertcat
:
>> tic; d2 = sscanf(strjoin(reshape(x,1,[])),'%f'); toc
Elapsed time is 0.068129 seconds.
>> isequal(d0,d2)
ans =
1
>> tic; d3 = sscanf(vertcat(x{:}).','%f'); toc
Elapsed time is 0.024312 seconds.
>> isequal(d0,d3)
ans =
1
>> tic; d4 = sscanf(str2mat(x).','%f'); toc
Elapsed time is 0.011917 seconds.
>> isequal(d0,d4)
ans =
1
注意:这些数字是大概数字,因为应该在脚本或函数内多次迭代运行,但所有代码都已预热。尝试一下。