Search code examples
matlabplotpiecewise

how to plot split function in MATLAB


I am trying to plot ONE graph in MATLAB that has two functions that take different domains.

f1(t) = 50*t              % 0<=t<15
f2(t) = 160/3)*t - 180    % 15<=t<=60

I tried using below

t1 = 0:15;
y = f1(t1)
plot(t1,y)
hold on

t2 = 15:60 ;
y = f2(t2)
plot(t2,y)
hold off

then I get TWO graphs that do not form a continuous line. the graph from the above code

I need the red graph starting at (15,750) I can cheat and move the starting point for the second graph to be (15,750) but is there a way I can graph these as one function?


Solution

  • One option is to define a single function where each term is multiplied by the condition for t, effectively zeroing it out when not applicable

    f = @(t) (50*t).*(t<15) + ((160/3)*t - 180).*(t>=15);
    
    t = 0:60;
    plot( t, f(t) );
    

    If your functions are complex then this could become slightly hard to read, but it's compact.