Conditional schedule?

I am trying to draw two functions, but I want to draw one function for a condition, but a graph using a different function if another condition is met.

A simple example would be:

if x> 0 then sin (x) else cos (x)

Then it will calculate cos and sin depending on the value of x, and there is an obvious gap at x = 0, since cos (0) = 1 and sin (0) = 0.

+3


source to share


1 answer


EDIT: there is a built-in way. I'll leave my original answer below for posterity, but try using the piecewise () function:

plot(piecewise(((cos(x),x<0), (sin(x), 0<x))))

      

Look at here.




I would guess there is a built-in way to do this, but I don't know. You can propagate your functions with the help

If x> 0, then heavy (x) = 1 and heavy (-x) = 0, so f (x) = sin (x).

If x <0, heavy (x) = 0 and heavy (-x) = 1, so f (x) = cos (x).

See it in action here . In general, note that if you wanted the transition to be at x = a, you could do the heavy (xa) and heavy (-x + a), respectively. If you want N functions, you will need to (N-1) multiply the step functions by each term, each with its own argument (x-a_i). I hope someone else can contribute cleaner solutions.

+2


source







All Articles