Plot Piecewise function graph
1 view (last 30 days)
Show older comments
Here's my code but i can't get the graph as shown in the picture.
% Use conditional statements and loops to calculate function values for
% different input ranges
x = -2.99*pi: 0.01: 3*pi; % Create domain from -2.99pi to 3pi, at increment of 0.01
y = zeros(1,length(x));
for i = 1: length(x) % For each statement i, it will pass through each value of x
if x(i) > -3*pi && x(i) < -pi % If x lies at −3pi < x <-pi,
y(i) = 1./log(2)*sin(x(i)); % the function is y = 1/(ln2)(sinx)
elseif x(i) >= -pi && x(i) <=2 % If x lies at -pi <= x <= 2,
y(i) = abs(x(i)) - 3; % the function is y = |x| -3
else
y(i) = exp(1); % If x doesn't lies at above interval, the function is y = e
end
end
plot(x, y);
text(3.2\pi, 0.2 , 'x'); text(0.2\pi, 3.5, 'y');
axis([-4\pi 4\pi -4 4]);
xticklabels({'-3\pi', '-2\pi', '-\pi', '0', '\pi', '2\pi', '3\pi'}); % Display tick marks along the x-axis by specifying the text to show pi symbol
yticks(-3: 1: 3); % Display tick marks along the y-axis 0.5,1 and 1.5
box off;
**This is the graph should be look like.
Answers (3)
Paul
on 9 Mar 2024
This line
y(i) = 1./log(2)*sin(x(i));
is incorrect.
The order of operations for multiplication and division is that they are evaluated in order from left to right. So that line could also be expressed as
y(i) = ( 1./log(2) ) * sin(x(i));
i.e., the division is done first, and the result of the division becomes the first operand for the multiplication.
Hopefully that gives you a clue as to how to fix the code (at least that part of it).
5 Comments
Paul
on 10 Mar 2024
Yes, those two lines do yield the same result. The first line is used in the code in the question. I used the extra parentheses in the second to emphasize the order of operations used to evaluate the first.
Neither of those lines are a correct implementation of
which was the point I was trying to make to lead the OP to the correct Matlab expression. I think the OP did eventually get the correct expression, but that comment has since been deleted.
Star Strider
on 9 Mar 2024
To do this in the Symbolic Math Toolbox, just write it essentially as in your original post —
syms x
f(x) = piecewise((-3*pi<x<-pi), 1/(log(2)*sin(x)), (-pi<=x<=2), abs(x)-3, (2<x<=3*pi), exp(1))
figure
fplot(f, [-4*pi 4*pi], 'MeshDensity',1E2)
grid
ylim([-1 1]*5)
.
2 Comments
Star Strider
on 10 Mar 2024
syms x
f(x) = piecewise((-3*pi<x<-pi), 1/(log(2)*sin(x)), (-pi<=x<=2), abs(x)-3, (2<x<=3*pi), exp(1))
figure
hfp = fplot(f, [-4*pi 4*pi], 'MeshDensity',1E2);
grid
hfp.ShowPoles = 'off'; % Turn Off All Asymptotes
xline(-3*pi, '--k') % Draw Asymptote At -3*pi
ylim([-1 1]*5)
.
See Also
Categories
Find more on Calculus in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!