2015-05-31 64 views
0

我有一個包含一些常量參數的matlab函數,我想用相同的圖形繪製該函數,使用hold(可能),同時改變那個常數。 這是我的代碼:如何使用hold命令繪製不同參數的matlab函數

close all 
clear all 
clc 
m = 5; 
x = 1:1:10; 
y = m*x + 10; 
h1 = figure; 
plot(x,y) 
m = 10; 
figure(h1); 
hold on 
plot(x,y,': r') 

當我使用此代碼試過,我有兩行對每個人的一致;它看起來像matlab只是使用參數m的最後一個值我怎麼能使它使用不同的值。 我發現了一些東西here,但不符合我的需求。 有什麼建議嗎?

回答

1

您需要重新計算y還有:

m = 5; 
x = 1:1:10; 
y = m*x + 10; 

h1 = figure; 
plot(x,y); hold on; 

m = 10; 
y = m*x + 10; 

figure(h1); 
plot(x,y,': r') 

或創建一個匿名函數:

x = 1:1:10; 
f = @(m) m*x + 10; 

%// and then: 
h1 = figure; 
plot(x,f(5)  ); hold on; 
plot(x,f(10),': r'); 
+0

然而,在我的實際情況中,我希望將其用於PID控制,其中我已經在一個文件(函數文件)中定義了我的參數和ODE方程,並且參數值和曲線在另一個m -file(運行文件),你可以檢查[this](http:// http://www.google.com.sa/url?sa = t&rct = j&q =&esrc = s&source = web&cd = 1&cad = rja&uact = 8&ved = 0CB4QFjAA&url = http%3A%2F%2Fstaff.kfupm.edu.sa%2FSE%2Fmshahab%2F081_ee656_hw5_sol_shahab.pdf&ei = DxVsVbCzFILbU-7hgIAF&usg = AFQjCNFeTZTAKkzjwgHv8F4XhUwvPZKIPQ)for two links robot。或者我應該發佈一個新問題?非常感謝。 – AlFagera

+0

@AlFagera我無法打開鏈接,但我猜這肯定是一個新問題。 – thewaywewalk

+0

@ thewaywewalk,對不起, [this](http://staff.kfupm.edu.sa/SE/mshahab/081_ee656_hw5_sol_shahab.pdf)是正確的鏈接。 – AlFagera

0

目前,你只更新m但你也必須重新計算y。這就是爲什麼當你發出第二個圖時,它繪製完全相同的y(即m仍然是5)函數。

你可能想使用一個簡單的for循環,像:

m = 5; 
x = 1:1:10; 
figure; 
hold on; 
for m=1:1:10 
    y = m*x + 10; 
    plot(x,y,': r') 
end 
+0

如果我想在這種情況下使用'for'循環來創建'legend',它將如何工作。 – AlFagera

+0

..看到我的其他答案。 –

0

除了short答案 - 提高plot ..

%% Data Preparations 
    x = 1:10; 
    ms = 3;    % number of different slopes 

    %% Graph Preparations 
    hold on; 

    % Prepare the string cell array 
    s = cell(1, ms); 

    % Handle storage 
    h = zeros(1, ms); 

    % Plot graphs 
    for m=1:ms 
     y = m*x + 10; 
     h(m)= plot(x,y,'Color',[1/m rand() rand()]); 
     s{m} = sprintf('Plot of y(m=%d)', m); 
    end 

    % Plot all or select the plots to include in the legend 
    ind = [ms:-1:1] .* ones(1,ms); % plot all 
    %ind = [ 1 3 4 ];    % plot selected 

    % Create legend for the selected plots 
    legend(h(ind), s{ind}); 

其他建議:當工作MATLAB和你試圖提高你的代碼的性能,你應該儘量避免使用for-loops,因爲MATLAB是MATrix操作,這就是它最擅長的。你已經採用了這個理念,你將創造出最美麗的代碼! ;)


此腳本通過Steve Lord的帖子。

相關問題