title: Inconsistencies in plotting piecewise functions in Matlab
body: <p>For a mathematics course for first year university science students we (the teaching assistants) need to prepare material for pc-sessions using Matlab. All computers are equipped with Matlab version R2016b. </p>
  
  <p><strong>We are working through some material from the previous years. In the section covering the plotting of piecewise functions, we found some inconsistencies in the way Matlab handles an <code>if</code> condition.</strong></p>
  
  <p>I would like to know why these things happen so we are prepared for any difficulties the students might experience in these sessions. The goal of the exercise is to draw a house in the plotting window by plotting two piecewise functions. </p>
  
  <hr>
  
  <p>The first function, <code>f1(x)</code>, evaluates to <code>x+2</code> when <code>x &lt;= 0</code> and evaluates to <code>-x+2</code> otherwise. The students are asked to implement this function in Matlab using an <code>if</code>/<code>else</code> construct. Our implementation is</p>
  
  <pre><code>function y = f1( x )
      if x &lt; 0
          y = x + 2;
      else
          y = -x + 2;
      end
  end
  </code></pre>
  
  <p>The second function, <code>f2(x)</code>, is the characteristic function of the interval [-1, 1]. It should also be implemented using <code>if</code>/<code>else</code> conditions. Our implementation is</p>
  
  <pre><code>function y = f2( x )
      if x &lt; -1
          y = 0;
      elseif x &gt; 1
          y = 0;
      else
          y = 1;
      end
  end
  </code></pre>
  
  <p>Finally, the plotting code should draw both functions on the interval <code>[-1.5, 1.5]</code> using <code>fplot</code> like so</p>
  
  <pre><code>fplot(@f1, [-1.5, 1.5])
  hold on
  fplot(@f2, [-1.5, 1.5])
  </code></pre>
  
  <hr>
  
  <p>The function <code>f2</code> is plotted without problems. <strong>In plotting <code>f1</code>, however, it seems Matlab decided the first branch of the if-clause didn't matter as only the line <code>-x+2</code> is plotted</strong>. </p>
  
  <p>It seems vectorization issues lie at the heart of our problem since <code>f1(-1)</code> evaluates correctly to 1 but <code>f1([-1, 1])</code> evaluates to <code>[3, 1]</code>. Then again, f2 seems to be evaluating correctly without any issues.</p>
  
  <p>Things get stranger when we change the <code>-x + 2</code> in the <code>else</code> part of <code>f1</code> to <code>-x^2 + 2</code>. With this definition both functions are plotted correctly and Matlab seems to have no problem dealing with the conditionals. </p>
  
  <ol>
  <li>What is going wrong? </li>
  <li>Is there a way we can edit the exercises such that it never poses any problems but is still accessible to students having their first experiences with Matlab?</li>
  </ol>