How can I create a cell array whose cells are strings based on a sequence of integers 1:N (for any N)?
Show older comments
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
More Answers (2)
Andrei Bobrov
on 26 Apr 2017
cellstr(string(1:3))
2 Comments
Guillaume
on 26 Apr 2017
or
cellstr(compose('%d', 1:3))
if you want more control over the formatting.
Richard Gunton
on 26 Apr 2017
C = sprintfc('%d', 1:3)
This is not documented, but exists for many years now.
4 Comments
Yes... very nice, but sadly undocumented. Has anyone put in a feature request?
Guillaume
on 26 Apr 2017
As of the introduction of compose (R2016b), sprintfc is no longer needed.
Stephen23
on 26 Apr 2017
@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.
Andrei Bobrov
on 27 Apr 2017
+1
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!