2015-03-02 43 views
1

我有一個向量,其條目我想成爲我的情節圖的標題。我怎麼做?我知道我只能給劇情加1個傳說。在Matlab中添加一個向量作爲傳說

n=[2 4 6 8 10]; 
legend(int2str(n)); 

它應該顯示爲5個不同的圖例,名爲「2」,「4」....,「10」。 我不是很熟悉如何將矢量n更改爲字符串矢量。 謝謝

回答

3

一個簡單而直觀的可能(在我看來)將創建與sprintf向量的每個元素對應的字符串。在我的例子中,我使用for-loop來生成曲線,但如果曲線是在其他地方生成的,這個想法也是一樣的。您可以根據需要自定義文本。該代碼基於與n中的元素一樣多的曲線。

例子:

clear 
clc 

x = 1:10; 

y = rand(1,10); 
n=[2 4 6 8 10]; 

%// Initialize the cell containing the text. For each "n" there is a cell. 
LegendString = cell(1,numel(n)); 

%// Plot every curve and create the corresponding legend text in the loop. 
hold all 
for k = 1:numel(n) 

    plot(x,n(k)*y) 
    LegendString{k} = sprintf('n = %i',n(k)); 
end 

%// Display the legend 
legend(LegendString) 

輸出:

enter image description here

希望這是你的意思。

對於一個班輪你可以使用arrayfunnum2str(感謝@Divakar您的建議):哪個讓你可以將呼叫直接使用legend單元陣列

arrayfun(@(n) ['n = ',num2str(n)],n,'Uni',0) 

+0

單行'arrayfun(@(n)['n =',num2str(n)],n,'Uni',0)'? – Divakar 2015-03-02 14:02:27

+0

非常感謝! – AndSchu 2015-03-02 14:22:07

+0

哈哈我從來沒有想過'arrayfun'好主意!您可以將其發佈爲答案我會+1 – 2015-03-02 14:22:17