In: Computer Science
Please use MATLAB.
Write a program to plot the piecewise function using IF statements and a FOR loop in MatLab. Use x as the input vector.
Plot from -20<=x<=20, increment of 1.
y = 4 x + 10 , ? ≥ 9,
y = 5? + 5, 0 ≤ ? < 9,
y = ?2 + 6? + 8, ? < 0
Plot each segment of the fn with different shaped points and a different color, for example, blue squares, cyan stars, red plus signs.
Use a FOR loop with IF statements to fill in the x vector. Do not define x as x=-20:1:20.
Code:
k = 1;
for j=-20:20
x(k) = j;
k = k+1;
end
for i=1:numel(x)
if x(i) < 0
y(i) = (x(i))^2 + 6*x(i) + 8;
elseif (x(i) >= 0) && (x(i) < 9)
y(i) = 5*x(i) + 5;
elseif x(i) >= 9
y(i) = 4*x(i) + 10;
end
end
% extracting piecewise values of x and y to plot with different markers
x1 = x(1:20); y1 = y(1:20);
x2 = x(21:29); y2 = y(21:29);
x3 = x(30:41); y3 = y(30:41);
plot(x1,y1,'-s','MarkerSize',10,...
'MarkerEdgeColor', 'blue')
hold on
plot(x2,y2,'-*','MarkerSize',10,...
'MarkerEdgeColor', 'cyan')
plot(x3,y3,'-+','MarkerSize',10,...
'MarkerEdgeColor', 'red')
hold off
(Feel free to throw an upvote or comment below if you have any doubts)