MATLAB Answers

the cyclist

Creating legend based on numeric array

Asked by the cyclist
on 1 Aug 2011

I have a numeric array, for example:

N = [1 7 14 30 90 180 360];

I want to create a cell array for use in a figure legend:

legendCell = {'N=1','N=7',...,'N=360'}

This is trivial to do with a loop, and I can think of a couple ways that avoid loops that are a bit kludgy. What is the most elegant way?

[The "N=" part is fixed and known. It does not have to be the variable name.]



5 Answers

Answer by Kelly Kearney
on 1 Aug 2011
 Accepted answer

One more:

 legendCell = cellstr(num2str(N', 'N=%-d'))

  1 Comment

Never noticed num2str could also specify format. Nice! +1

Answer by Jan Simon
on 1 Aug 2011

N = [1 7 14 30 90 180 360];
C = regexp(sprintf('N=%d#', N), '#', 'split');
C(end) = [];

Another solution: In older MATLAB versions DATAREAD (called as core function through STRREAD) was faster. But unfortunately these functions are deprecated. Now TEXTSCAN helps:

CC = textscan(sprintf('N=%d#', N), '%s', 'Delimiter', '#');
C = CC{1};

  1 Comment


Answer by Fangjun Jiang
on 1 Aug 2011


Or better for N could be column vector or row vector



Answer by Oleg Komarov
on 1 Aug 2011

Hidden loop (troll):

arrayfun(@(x) sprintf('N=%d',x),N,'un',0)

Based on Kelly's idea of '%-d':


  1 Comment


Answer by Paulo Silva
on 1 Aug 2011

My kludgy way:

legendCell = eval(['{' sprintf('''N=%d'' ',N) '}'])


Paulo, your first solution returns 1x1 cell

that's why I edited my question and removed it :)

I like the kludgy way. Seeing so many eval must have made a dent on your brain.

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!