Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab: converting a vector to a cell array of strings

Tags:

cell

matlab

I'm sure there's a way to do this but I don't know what it is.

Suppose I have a vector

v = [1.02 2.03 3.04];

and I want to convert this to a cell array using a format string for each element:

'   %.3f'

(3 spaces before the %.3f)

How can I do this? I tried the following approach, but I get 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.
like image 206
Jason S Avatar asked May 30 '12 14:05

Jason S


3 Answers

As stated in the error, just provide the parameter of UniformOutput as false

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

ans = 

    '   1.020'    '   2.030'    '   3.040'
like image 74
petrichor Avatar answered Oct 29 '22 06:10

petrichor


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 transpose the result if you want a row vector.

like image 45
Amro Avatar answered Oct 29 '22 07:10

Amro


You can also use the {} syntax:

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

Also check out : Applying a function on array that returns outputs with different size in a vectorized manner

like image 23
Andrey Rubshtein Avatar answered Oct 29 '22 07:10

Andrey Rubshtein