piecewise function is a special function that has a very particular
along the independent values. For some values of x, the function has
a constant or a formula, but for other values of x, it has associated
formula. Each section is called a piece of the function.
Scilab programming, there’s a number of methods to achieve this kind of
functions. We could use branches (if-else code), or different cases
(switch-case code), and iterations (for or while-loops) in general. In
example, we’re going to use a vectorized approach...
Piecewise functions in Matlab
we have to understand some useful built-in functions or Scilab features
have a vector like this
-6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
find a range of values and a range of indices for those values.
x(-4 < x & x <= -3)
going to generate a vector of x-values that meet the condition -4 < x <=
-3. Notice the particular syntax. The line uses a
conditional range (extraction
of values from a vector) including an ‘and’ operation (&). It
gives us the
x-values that meet both conditions -4 < x and x <= 3.
x-vector above, the result would be just one value
< x & x <= -3)
going to generate a vector of indices of the values generated before.
particular case, the result would be
5 is the index of the value -3 in the given vector x.
need to take care of both the values and the corresponding indices in a
let’s say that we have a 4-piece function like this one:
design a Scilab function to perform like that described one. It’s
piecewise3.sci and accepts a vector as input:
function y = piecewise3(x)
first piece - a constant
<= -4)) = -1;
second piece - a straight line
x(-4 < x & x <= -3);
< x & x <= -3)) = -4*x2 - 13;
third piece - a parabola
x(-3 < x & x <= 0);
< x & x <= 0)) = x3.^2 + 6*x3 + 8;
fourth piece - another constant
< x)) = 8;
general idea is to find the x-values for the different pieces of the
and then apply the corresponding formula just to those values.
Finally, we have
to find the correct indices in the output vector to place those values.
one piece at a time. In the first and fourth pieces above, we don’t
find the x-values, because the function is a constant. We just have to
indices where the constants are going to be placed.
call the code from our main script or from any other sci-file, like
Reset the environment
declare the function to be called
define your independent values in a column row
x = [-7
: .1 : 7]';
your previously defined function
resulting plot is this:
Another Example - Vectorization
'Scilab Piecewise Function' to Matlab home
'Scilab Piecewise Function' to Scilab Examples