Search code examples
functionmatlabpiecewise

Define a piecewise function with three variables


I am trying to define a function in MATLAB according to the following conditions:

If t<0 
     f(t,x,y)=t*(x/y)+1.
else
     f(t,x,y)=-t*(x/y)+1.
end

I found a way to define a piecewise function in one variable, but here I have three variables. Is there a way to define such a function in MATLAB?


Solution

  • The following creates an anonymous function with the equation you describe above

    f = @(t,x,y) -abs(t) * (x/y) + 1;
    

    Then you can use it like a normal function:

    y = f(tData,xData,yData);
    

    If it's more complicated than that, then it needs to be a sub-function, nested function or private function.