3

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?

Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
Fatimah
  • 169
  • 2
  • 3
  • 10
  • 1
    I'm confused as to why you need a piecewise function for this. Surely the function `f(t,x,y) = -abs(t) * (x/y) + 1` satisfies the conditions? – Bill Cheatham Jan 26 '12 at 16:08

2 Answers2

1

If I understand correctly, you need to do 3 ifs. I will show you how to do it for 2 variables:

If t<0 
  if x<0
     %Case 1
  else
     %Case 2           
  end
else
  if x<0
     %Case 3
  else
     %Case 4
  end

end

Alternatively, you can use 2^3=8 if-elseifs. Or, in 2 variables case - 2^2 = 4.

 if t<0 && x<0
     %Case 1      
 elseif t<0 && x>0
     %Case 2     
 elseif t>0 && x>0
     %Case 3
 else
     %Case 4
 end
Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
1

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.

Nzbuu
  • 5,241
  • 1
  • 29
  • 51