我提出了5个额外的解决方案,其中三个比目前提出的解决方案快4-5倍。从中学到的教训是:
num2str
很慢
cellfun
和 arrayfun
可能会增加很大开销
- 有很多方法可以将数字数组转换为字符串单元格数组。
在性能方面表现最好的三个解决方案非常相似:
循环分配单元格元素
n4 = length(Keyset);
tmp4 = cell(n4,1);
for i4 = 1:n4
tmp4{i4} = sprintf('%i',Keyset(i4));
end
将所有内容转换为字符串并调用
textscan
tmp6 = textscan(sprintf('%i\n',Keyset'),'%s');
tmp6 = tmp6{1};
将所有内容转换为字符串并调用
regexp
。
tmp3 = regexp(sprintf('%i ',Keyset),'(\d+)','match');
以下是带有时间的完整测试代码:
function t = speedTest
t=zeros(7,1);
for ii=1:100,
Keyset=randi(1,10,100);
tic;
eval( [ 'tmp1 = { ', sprintf(' %d ', Keyset), ' }; '] );
t(1)=t(1)+toc;
tic;
tmp2=arrayfun(@num2str, Keyset, 'Uniform', false);
t(2)=t(2)+toc;
tic;
tmp3 = regexp(sprintf('%i ',Keyset),'(\d+)','match');
t(3) = t(3)+toc;
tic;
n4 = length(Keyset);
tmp4 = cell(n4,1);
for i4 = 1:n4
tmp4{i4} = sprintf('%i',Keyset(i4));
end
t(4) = t(4)+toc;
tic;
n5 = length(Keyset);
tmp5 = cell(n5,1);
for i5 = 1:n5
tmp4{i5} = num2str(Keyset(i5));
end
t(5) = t(5)+toc;
tic;
tmp6 = textscan(sprintf('%i\n',Keyset'),'%s');
tmp6 = tmp6{1};
t(6) = t(6)+toc;
tic;
tmp7 = num2cell(Keyset);
tmp7 = cellfun(@(x)sprintf('%i',x),tmp7,'uni',false);
t(7) = t(7)+toc;
end;
t
t =
1.7820
21.7201
0.4068
0.3188
2.2695
0.3488
5.9186
{'203','2','12','39'}
吗? - Eitan T