我提出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); % random keys
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'}'? –