How to make a graph of a three-branches function in matlab

后端 未结 2 338
名媛妹妹
名媛妹妹 2021-01-16 04:35

How can I make this function\'s graph in Matlab, so that its body is depicted in the same graph (plot or subplot)?

    t0=0.15 
    x(t)= 1, if 0<=t<(         


        
2条回答
  •  终归单人心
    2021-01-16 05:24

    The real question you should be asking is "How to define a function that has branches?", since plotting is easy once the function is defined.

    1. Here's a way using anonymous functions:

      x_t = @(t,t0)1*(0<=t & t

      Note that the & operator expects arrays and not scalars.

    2. Here's a way using heaviside (aka step) functions (not exactly what you wanted, due to its behavior on the transition point, but worth mentioning):

      x_t = @(t,t0)1*heaviside(t)+(-1-2)*heaviside(t-t0/2)+2*heaviside(t-t0*3/2);
      

      Note that in this case, you need to "negate" the previous heaviside once you leave its area of validity.

    After defining this function, simply evaluate and plot.

    t0 = 0.15;
    tt = -0.1:0.01:0.5;
    xx = x_t(tt,t0);
    plot(tt,xx); %// Or scatter(), or any other plotting function
    

    BTW, t0 does not have to be an input to x_t - if it is defined before x_t, the value of t0 that exists in the workspace at that time will be captured and used, but this also means that if t0 changes later, this will not affect x_t.

提交回复
热议问题