Creating legend based on numeric array

141 ビュー (過去 30 日間)
the cyclist
the cyclist 2011 年 8 月 1 日
コメント済み: Fangjun Jiang 2020 年 9 月 16 日
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.]

採用された回答

Kelly Kearney
Kelly Kearney 2011 年 8 月 1 日
One more:
legendCell = cellstr(num2str(N', 'N=%-d'))
  3 件のコメント
TheStranger
TheStranger 2020 年 9 月 16 日
But how one can insert a special tex-symbols like \omega and such in there? It throws an error.
Fangjun Jiang
Fangjun Jiang 2020 年 9 月 16 日
use sprintf(), see special character section, get the unicode

サインインしてコメントする。

その他の回答 (5 件)

Steven Lord
Steven Lord 2020 年 9 月 16 日
If you're using a newer release of MATLAB, I'd use a string array to create the legend.
N = [1 7 14 30 90 180 360];
x = linspace(0, 1, 17);
plot(x, N.*x.')
legendStrings = "N = " + string(N);
legend(legendStrings)

Jan
Jan 2011 年 8 月 1 日
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 件のコメント
Oleg Komarov
Oleg Komarov 2011 年 8 月 1 日
regexp(sprintf('N=%d',N),'N=\d+','match')

サインインしてコメントする。


Paulo Silva
Paulo Silva 2011 年 8 月 1 日
My kludgy way:
legendCell = eval(['{' sprintf('''N=%d'' ',N) '}'])
  3 件のコメント
Paulo Silva
Paulo Silva 2011 年 8 月 1 日
that's why I edited my question and removed it :)
Fangjun Jiang
Fangjun Jiang 2011 年 8 月 1 日
I like the kludgy way. Seeing so many eval must have made a dent on your brain.

サインインしてコメントする。


Fangjun Jiang
Fangjun Jiang 2011 年 8 月 1 日
legendCell=strcat('N=',strtrim(cellstr(num2str(N'))))
Or better for N could be column vector or row vector
legendCell=strcat('N=',strtrim(cellstr(num2str(N(:)))))

Oleg Komarov
Oleg Komarov 2011 年 8 月 1 日
Hidden loop (troll):
arrayfun(@(x) sprintf('N=%d',x),N,'un',0)
Based on Kelly's idea of '%-d':
cellstr(reshape(sprintf('N=%-3d',N),floor(log10(abs(max(N))+1))+3,numel(N)).')
  1 件のコメント
Andrei Bobrov
Andrei Bobrov 2011 年 8 月 1 日
+1

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by