5

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.
3
  • 2
    Doh! I wish the error messages were a little more clear. Something like You may wish to use cellfun(..., 'UniformOutput', false) Commented May 30, 2012 at 14:18
  • By the way, definitely you are familiar but I learned recently that sprintf works in arrays: i.e. you can use sprintf(' %.3f',v) to print all elements. Maybe, you are creating the cells for sth like this? Commented May 30, 2012 at 14:20
  • That was another possibility (convert to a 2-D string, then to cell array) but has the disadvantage that it pads the rows of the string with spaces. Commented May 30, 2012 at 14:25

3 Answers 3

6

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Or use the {} syntax - cellfun(@(x){f1(x)}, num2cell(v))
2

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.