Matlab: converting a vector to an array of row cells

I am sure there is a way to do this, but I do not know what it is.

Suppose I have a vector

v = [1.02 2.03 3.04];

and I want to convert it to an array of cells using a format string for each element:

'   %.3f'

(3 spaces before% .3f)

How can i do this? I tried the following approach, but getting an error:

>> f1 = @(x) sprintf('   %.3f',x);
>> cellfun(f1, num2cell(v))
??? Error using ==> cellfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.
+5
source share
3 answers

As indicated in the error, simply specify the parameter UniformOutputasfalse

cellfun(f1, num2cell(v), 'UniformOutput', false)

ans = 

    '   1.020'    '   2.030'    '   3.040'
+6
source

Here is another solution:

>> v = [1.02 2.03 3.04];
>> strcat({'   '}, num2str(v(:),'%.3f'))
ans = 
    '   1.020'
    '   2.030'
    '   3.040'

Obviously, you can transfer the result if you want a row vector.

+2
source

{}:

 cellfun(@(x){f1(x)}, num2cell(v)) 

: ,

+1
source

All Articles