We can also use “linspace” command to create an array. The array x specifies the range of values on which we want to obtain the results of the piecewise function. Then, we have used a for loop which iterates over an array x and passes these values to the “piecewise_function”. The “piecewise_function” takes the value and check the conditions of if-else statements. Here, if-else conditions are used to check the interval where the input(x) lies. As the value of x lies in the (0,2] interval, therefore, the x will enter into the body of the 2nd elseif condition. In this case, the body of the if statement consists of only one statement which is ” result = x.^2 “. The values calculated are stored into an array ‘result’ which represents the piecewise function values with respect to input (x). Output: Figure 3 using switch-case statements The plot(x, result) command plots the values in variable “result” against ‘x’. It is almost similar to the above method but in this case, we have replaced the if-else with switch-case statements. We have separated the intervals of different sub-functions in different cases. First of all, the case expressions check the value of x. # Plotting Piecewise function using switch case statements If the ‘case’ condition is true, then that means x lies in the interval specified by that case expression and the appropriate statements will be executed. The vectorized method By using If-Else statements The MATLAB provides a built-in function “piecewise” which takes the equations and conditions as an argument and returns a piecewise expression.3. To implement the above function in Matlab first we need to create one function with keyword ‘ piecewise ’ Plot ( input variable, output variable )įunction output variable = piecewise ( input variable ) This is one of the basic terminologies to implement piecewise functions but, this is not a good practice to implement piecewise function. In the above statement ‘ f x ’ is the name of the output variable, ‘ piecewise ’ is keyword used for the above function and ‘ x ’ is the input variable.Īfter declaring function now we need to define the conditions of ranges of input variable ‘ x’. In above statements if-else statement is used to define the range. it shows that if the value of x is less than or equal to ‘ 0 ’ then out will be ‘ – 2 ’ and if the value of ‘ x ’ is more than ‘ 0 ’ then the output will be ‘ 2’. The second method in loops is driven by switch-case statements. In this method we represent different conditions in different methods, we can specify multiple cases in one switch loop. #Plotting piecewise functions in matlab code#.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |