【问题标题】:How to plot a matlab function for different parameters using hold on command如何使用 hold on 命令绘制不同参数的 matlab 函数
【发布时间】:2015-06-01 22:23:06
【问题描述】:

我有一个包含一些常量参数的 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,但不能满足我的需求。 有什么建议吗?

【问题讨论】:

    标签: matlab plot matlab-figure


    【解决方案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');
    

    【讨论】:

    • 一切都很好,但是,在我的实际情况下,我想将其用于 PID 控制,我将参数和 ODE 方程定义在一个文件(函数文件)中,以及参数值和绘图在另一个 m 文件(运行文件)中定义,您可以检查 this 以获得两个链接机器人。还是我应该发布一个新问题?非常感谢。
    • @AlFagera 我无法打开链接,但我想这绝对是一个新问题。
    • @thewaywewalk,对不起; [this] (staff.kfupm.edu.sa/SE/mshahab/081_ee656_hw5_sol_shahab.pdf) 是正确的链接。
    【解决方案2】:

    目前,您只更新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
    

    【讨论】:

    • 如果我想在这种情况下使用for循环制作legend,它将如何工作。
    • .. 看看我的其他答案。
    【解决方案3】:

    除了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 循环,因为 MATLAB 是 MATrix 操作,而这是它最擅长的。如果您采用了这种理念,您将创建最漂亮的单行代码! ;)


    这个脚本是对Steve Lord的帖子的采用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多