and we’d choose to graph iton the domain of -8 ≤ x ≤ 4
Method 1. If-else statements
Notice that this is notthe best way to execute it inMatlab, however I point out the idea because this is the fundamentalconcept, and in some programming language it can not be excellent in adfferent way. It"s for study, not for real implementation...
So, let"s define ourfunction with if-else statements for the moment. Wejust usage different problems for the different ranges, and assignappropriatevalues.
function y =piecewise1(x)if x y= 3;elseif -4 y= -4*x - 13;elseif -3 y= x^2 + 6*x + 8;else y = 8;end Now, we have the right to use scalarsor arrays to call this function, ina classical way:
%Define elementsx = <-5-4 -3 0 3>%Submit element-by-element come the functionfor ix = 1: length(x) y(ix)= piecewise1(x(ix))end%Plot discrete valuesplot(x,y, "ro")%Define x and y arrays to displayaxis(<-84 -2 10>) The result is:
Method 2. Switch-case statementsOur 2nd methodclassifies the elements using switch-case statements.We different the various ranges in various cases. If that conditionis true,then the switch-expression will enhance the case-expression, and theappropriatestatement(s) will be executed.function y = piecewise2(x)switch x % Ascalar switch_expr matchesa case_expr if %switch_expr == case_expr % Thefirst case must coverthe x = 0 situation case x * (-3 y = x^2 + 6*x + 8; situation x * (x y = 3; case x * (-4 y = -4*x - 13; otherwise y = 8;endOne necessary note is that once x = 0 the result of thecase-expression is likewise 0, and also the very first case is executed. That’s whyweneed toplace our x = 0 case an initial in the structure, otherwise we gain wrongthat point.We have the right to test our secondpiecewise function definition, likethis: x= -8 :.01 : 4;for ix = 1: length(x) y(ix)= piecewise2(x(ix));endplot(x,y)axis(<-84 -2 9>) and gain the previousshown graph, too.
Method 3. Vectorized wayThe above routines assumethat we’re entering scalars asinput parameters. Now, we’ll assume the we’re submitting wholevectors, andwe’ll manage indices for that.This video clip will present youhow to carry out it without using loops. After ~ the video, one more example isgiven with full code.
See more: Gwen Stefani Rare Lyrics - Lyrics For Rare By Gwen Stefani