I offer 5 additional solutions, three of which are 4-5 times faster than the proposed solutions. The following lessons can be learned from this:
num2str slowcellfun and arrayfun can add significant overhead- There are many ways to convert a numeric array into an array of row cells.
Three high-performance solutions are very similar in performance:
Looping to Assign Cell Elements
n4 = length(Keyset); tmp4 = cell(n4,1); for i4 = 1:n4 tmp4{i4} = sprintf('%i',Keyset(i4)); end
Convert everyone to string and call textscan
tmp6 = textscan(sprintf('%i\n',Keyset'),'%s'); tmp6 = tmp6{1};
Convert everyone to string and call regexp .
tmp3 = regexp(sprintf('%i ',Keyset),'(\d+)','match');
Here is the full test code with timings:
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