Piecewise Functions in Matlab
MatrixLab Examples
For detailed codes in Matlab and more examples, visit:
http://matrixlab-examples.com/piecewise-function.html
This video will give you an idea of how to work with piecewise functions in Matlab.
A piecewise function is a function which is defined by multiple sub functions, and each one applies to a certain interval of the main function's domain.
I’ll show one way to define and plot them in Matlab without using loops. I’ll use a vectorized way: no scalar values or iterations will be used.
Let’s think of a function with 4 different sub functions that apply in different intervals. The first interval shows a constant, the second interval shows a straight line, the third one is a parabola and the last interval is another constant. It’s just an example, the sub functions could be anything...
This is the plot of the piecewise function in our range of interest, displaying the different pieces.
Ideally, we should type something like this and get the given plot: we define our range of interest, define the function and plot it as with any other function.
Our goal in this example is to define the function without iterations. We’ll use only full intervals. To accomplish this, we’ll use two ideas: specially selected indices and the function find.
The first important concept that we need is the use of special indices. In Matlab, we can extract some values of a vector if we type a given condition for the indices of that vector.
The second important concept that we need to know is that the built-in function find finds specific indices (not values) of the values in a vector that meet a condition.
Now, we put it all together and define our function. We give it a name, we get our input vector in x, and let y be our output vector.
The first interval of the piecewise function was defined as a constant. We just need the indices of the output vector where we’ll put that constant.
For the second interval we do need the values of the input vector that are within the interval and also need the indices of those values.
For the third interval we also need the values and their indices.
The fourth interval is like the first one, we don’t need the values of the input vector because this piece is a constant. We just need the indices.
This is the final code, just as you’d type it. As you can see the main ideas are very simple.
You can call that function from your main code or from your command window, just like this...
5372696 Bytes