2015-02-07 90 views
2

首先,我想弄清楚一個更復雜的情況,但這是我可以提供的最小例子。假設我想在一個普通的人物中展示3個函數sinx, sin(2x), sin(3x)的圖表,包括他們的傳說。在MATLAB和圖例中繪製

我可以在普通圖中繪製圖形,但我有legend.問題我爲您提供了我的算法(對不起,不是優化的算法,但我沒有太多的書寫算法)。

x = 0:0.01:2*pi; 
for i = 1:3 
    g = plot(sin(i*x)); 
    legend(sprintf('sin(%f *x)', i)) 
    hold on 
end 
hold off 
g 

如果你能幫助我修復我的算法,那將會很好。

回答

1

你可以通過DisplayNameplot功能

x = 0:0.01:2*pi; 
for i = 1:3 
    g = plot(sin(i*x),'DisplayName',sprintf('sin(%.0f *x)', i)); 
    hold on 
end 
hold off 
legend('Show','Location','NorthEast') 

enter image description here

+0

很不錯的。我不知道'DisplayName'屬性 – 2015-02-07 19:58:21

0

你想要什麼可以沒有循環來完成:

  • 使用bsxfun計算的每個i倍產品矢量x,然後計算該臨時表的sin噸。這給你一個矩陣,s。構建矩陣,使每個i s不同
  • 只需發出plot(s)。當您將矩陣傳遞到plot時,會生成每個的圖表。
  • 構建一個包含字符串的單元格數組(您可以使用arrayfun),並將其用作legend的輸入參數。

代碼:

x = 0:0.01:2*pi; 
ii = 1:3; 
s = sin(bsxfun(@times, ii, x.')); 
plot(s) 
str = arrayfun(@(k) ['sin(' num2str(k) '*x)'], ii, 'uniformoutput', false); 
legend(str) 

結果:

enter image description here