Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Defining piecewise function in matlab

  1. Oct 27, 2010 #1
    How would you write piecewise functions in matlab that can take vector inputs?

    Here's a function that I'm trying to write.
    Code (Text):

    function y=g(x)
    if x==0
    If I call g([0,pi/2]), I want it to return [0,2/pi], but what I get instead is [NaN,2/pi]. I'm guessing when I write x==0, matlab is comparing the entire input to 0.
  2. jcsd
  3. Nov 3, 2010 #2
    Try this to eliminate the problem at x=0.

    g = @(x) 1.*(x==0) + (x~=0).*sin(x)./(x+(x==0));
    t=[0 pi/2];
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Similar Discussions: Defining piecewise function in matlab