and we’d like to graph iton the domain of -8 ≤ x ≤ 4
Method 1. If-else statements
Notice that this is notthe best way to do it inMatlab, but I mention the idea because this is the fundamentalconcept, and in some programming languages it cannot be done in adfferent way. It"s for study, not for real implementation...
So, let"s define ourfunction with if-else statements for the moment. Wejust use different conditions 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 can use scalarsor arrays to call this function, ina classical way:
%Define elementsx = <-5-4 -3 0 3>%Submit element-by-element to the functionfor ix = 1: length(x) y(ix)= piecewise1(x(ix))end%Plot discrete valuesplot(x,y, "ro")%Define x and y ranges to displayaxis(<-84 -2 10>) The result is:
Method 2. Switch-case statementsOur second methodclassifies the elements using switch-case statements.We separate the different ranges in different cases. If that conditionis true,then the switch-expression will match 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 case case x * (-3 y = x^2 + 6*x + 8; case x * (x y = 3; case x * (-4 y = -4*x - 13; otherwise y = 8;endOne important note is that when x = 0 the result of thecase-expression is also 0, and the first case is executed. That’s whyweneed toplace our x = 0 case first in the structure, otherwise we get wrongthat point.We can 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 get the previousshown graph, too.
Method 3. Vectorized wayThe above routines assumethat we’re entering scalars asinput parameters. Now, we’ll assume that we’re submitting wholevectors, andwe’ll handle indices for that.This video will show youhow to do it without using loops. After the video, another example isgiven with full code.
See more: Gwen Stefani Rare Lyrics - Lyrics For Rare By Gwen Stefani