【问题标题】:Matlab plot for many branches (piecewise function)许多分支的Matlab图(分段函数)
【发布时间】:2016-11-15 17:46:35
【问题描述】:

我想绘制以下函数

I(x) = 5*(1+x/2) for -2 < x < 0
       5*(1-x/2) for  0 < x < 2
       0     elsewhere

我使用以下脚本:

clc; close all; clear all;
L = 4;
x = -20:1:20;
I((-L/2) < x & x<0) = 5*(1 + x/(L/2));
I(0 < x & x < (L/2)) = 5*(1 - x/(L/2));
plot (x,I), grid

它不起作用。你能帮帮我吗?

【问题讨论】:

    标签: matlab if-statement plot piecewise


    【解决方案1】:

    您还需要为每个条件选择要使用的x 值。像这样的:

    L = 4;
    x = -5:0.1:5;
    I = zeros(size(x));
    cond1 = (-L/2)<x & x<0;
    cond2 = 0<x & x<(L/2);
    I(cond1) = 5*(1 + x(cond1)/(L/2));
    I(cond2) = 5*(1 - x(cond2)/(L/2));
    plot (x,I), grid
    

    不确定在x=0x=-2x=2 的边界条件下要做什么。但是你只需要修改cond1cond2即可。

    【讨论】:

      【解决方案2】:

      Symbolic Math Toolbox 中新增了一个分段函数:piecewise

      所以

      syms x
      y = piecewise(-2<x<0,5*(1+x/2),0<x<2,5*(1-x/2),0);
      fplot(y)
      

      【讨论】:

        猜你喜欢
        • 2023-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多