1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Piecewise Function in MATLAB

  1. Mar 30, 2014 #1


    User Avatar
    Homework Helper

    1. The problem statement, all variables and given/known data

    Hey there. I'm trying to plot a piecewise function in MATLAB and I'm having some decent success, but there's some things I'm wondering.

    Here's the function: http://gyazo.com/d3493a0c13096878acf5a501af8a7f66

    2. Relevant equations

    3. The attempt at a solution

    My strategy was to create an empty array to hold all the y values since plotting the x values is easy enough. I came up with this short snippet of code:

    Code (Text):
    function plotFunction()
    y = []; %Empty array to hold the y values

    for i=-40:0.05:30
        if i <= 0
            y(end+1) = 38/11 + sin(i^2);
        elseif i <= 9
            y(end+1) = 38/(11-i);
            y(end+1) = 1.5*sqrt(4*i) + 10;

    plot(-40:0.05:30, y);
    title('Piecewise Function Plot');

    This code yields the following plot, which is really close, but there's something wrong:


    What's with the funky activity near ##x = -30##? Why does it get all clumped up around there?

    I tried tinkering with the increment of 0.05, but shrinking it clumps the graph together even more.
  2. jcsd
  3. Mar 30, 2014 #2
    It's an artifact of sampling the waveform and plot doing linear interpolation. Try, for instance, to use an increment of 0.001 instead.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted