How can I create a cell array whose cells are strings based on a sequence of integers 1:N (for any N)?

I want my function to add a legend to a plot where the legend has a variable number of items depending on N: e.g. '1', '2', '3' if N=3. The help file tells me I can use a matrix or a cell array: legend(M). But I can't find a way of creating a suitable array without fixing the number of cells. For example,
num2cell(1:N)'
doesn't help because legend() only seems to accept cell arrays containing strings, not numeric values. And int2str() doesn't help because it adds spaces in between the numbers.

 Accepted Answer

This works for any MATLAB versions:
>> arrayfun(@num2str,1:3,'Uni',0)
ans =
'1' '2' '3'

More Answers (2)

C = sprintfc('%d', 1:3)
This is not documented, but exists for many years now.

4 Comments

As of the introduction of compose (R2016b), sprintfc is no longer needed.
@Guillaume: I am not totally convinced about that. The main advantage of sprintfc is speed: it really is very fast. And given the significantly larger memory requirements of strings compared to simple numeric/char arrays, I think some performance comparisons are required before declaring sprintfc to be superfluous.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!