9

How would you efficiently build a cell array of strings which contain numbers (in my particular case, a cell array of labels for a legend).

Eg:{'series 1', 'series 2', 'series 3'}

I've tried things along the lines of

sprintf('series %i', {1:10})

but apparently sprintf and cell arrays don't play nice together.

Something like this works if I only want the number, but doesn't work if I want text as well.

cellstr(int2str([1:10]'))

Obviously, it can be done in a loop, but there must be a clever one-liner way of doing this.

4 Answers 4

12

I know it's been 4 years but I came across the undocumented function sprintfc which is used to do exactly what you want:

CellArray = sprintfc('series %i',1:3);

CellArray = 

    'series 1'    'series 2'    'series 3'

well... it might be useful to someone I guess.

Sign up to request clarification or add additional context in comments.

1 Comment

great! Glad someone found out this post :)
6

The functions INT2STR and STRCAT do the trick:

>> cellArray = strcat({'series '},int2str((1:3).')).'

cellArray = 

    'series 1'    'series 2'    'series 3'

Comments

3

A slightly different way:

cellArray = cellstr( num2str((1:3)', 'series %d') )

or alternatively

cellArray = strcat( num2str((1:3)', 'series %d'), {} )

with the result:

cellArray = 
    'series 1'
    'series 2'
    'series 3'

Comments

3

You can use the one-liner below for more complicated output:

cellarray = arrayfun(@(x) {sprintf('item %d of 3', x)}, 1:3)

cellarray = 

    'item 1 of 3'    'item 2 of 3'    'item 3 of 3'

1 Comment

Yes! This! You solved my problem, the other solutions dont work for more involved outputs. I originally made a loop that did not work when used as input for legend(): for ii=1:n;cellArray{ii}={sptrinf('n %d, val %0.2f', ii, vals(ii))};end

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.