string - MATLAB: populate cell array and format number -


what's efficient way populate cell array values vector (each formatted differently).

for example:

v = [12.3 .004 3 4.222]; 

desired cell array:

array = {'a = 12.30' 'b = 0.004' 'c = 3' 'd = 4'}; 

is there easier way calling sprintf each , every cell?

array = {sprintf('a = %.2f',v(1)) sprintf('b = %.3f',v(2)) ... } 

there's no vectorized form of sprintf supports different formats, you're stuck sprintf call per cell. arrange code easier deal in loop.

v = [12.3 .004 3 4.222]; names = num2cell('a':'z'); formats = { '%.2f' '%.3f' '%d' '%.0f' };  c = cell(size(v)); = numel(v)     c{i} = sprintf(['%s = ' formats{i}], names{i}, v(i)); end 

it tricky faster naive way without dropping down java or c, because it's still going take sprintf() call each cell, , that's going dominate execution time.

if have large number of elements , relatively small number of formats, use unique() group them in 1 sprintf() call per format, using vectorized version of sprintf , splitting on delimiter individual strings. may or may not faster, depending on exact data set , implementation.

or write mex file pushes loop down in c, looping on call c's sprintf. faster, once moderately large input sizes.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -