【问题标题】:How do I hold multiple functions in an array in MATLAB?如何在 MATLAB 的数组中保存多个函数?
【发布时间】:2010-12-05 06:24:19
【问题描述】:

我是 MATLAB 的新手,所以我什至不知道这是否可能,但它是... 我正在尝试使用 plot 函数在单个图形中打印多条线。问题是,我希望能够通过简单地更改变量来指定图形应该显示多少行,例如:{This is the pseudo code to what I want to do}

 number_of_lines = 4;
 x = 0:0.5:5;

 function_output[number_of_lines];

 for n=0:number_of_lines
     function_output[n] = sin(n + x);
 end

 for n=0:number_of_lines
     plot(x,function_output[n]);
 end

我知道上面的伪代码并不完全是 MATLAB,但我只想知道这种算法是否可以在 MATLAB 中完成。

【问题讨论】:

    标签: arrays matlab plot


    【解决方案1】:

    这是在 MATLAB 中实现示例的一种方法:

    function_output = zeros(numel(x), number_of_lines);  % Initialize a 2-D array
    for n = 1:number_of_lines                   % MATLAB uses 1-based indexing
        function_output(:, n) = sin(n + x).';  %' Compute a row vector, transpose
                                                %   it into a column vector, and
                                                %   place the data in a column of
                                                %   the 2-D array
    end
    plot(x, function_output);  % This will plot one line per column of the array
    

    以下是一些文档链接,您应该通读以了解和理解上述代码:

    【讨论】:

      【解决方案2】:

      您看过 MATLAB 手册吗? - 它写得很好,有很多例子。复制示例脚本并将它们粘贴到命令行窗口,看看会发生什么...

      http://www.mathworks.com/help/techdoc/creating_plots/f9-53405.html

      您可以编写脚本或使用他们的绘图工具: http://www.mathworks.com/help/techdoc/creating_plots/f9-47085.html

      --- 脚本示例

      number_of_lines = 4;

      x = 0:0.5:5;

      function_output=ones(number_of_lines,1)*nan;

      图;等一下;

      对于 n=1:number_of_lines

      function_output(n,1) = plot(x,sin(n+x),'color',[1-n/number_of_lines 0 n/number_of_lines]);

      结束

      图例(函数输出)

      玩得开心。

      【讨论】:

      • 问题:如果我只想在 x 为 3 时绘图怎么办。if 语句应该是 if(x == 3) 吗?
      • 如果我理解正确(我猜这里),你希望只绘制 n==3 吗?换句话说,您只想绘制第三行?如果是这种情况,是的 - 您可以添加: if (n==3); ;结束
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 2014-04-28
      • 2013-04-26
      • 1970-01-01
      相关资源
      最近更新 更多