Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

MATLAB... -Must use for loop -Must use zeros function -Must use else function Gi

ID: 3815075 • Letter: M

Question

MATLAB...

-Must use for loop

-Must use zeros function

-Must use else function

Given the following piecewise function, f(x):

f(x)= x + 3 when x < -3

f(x)= -2x - 6 when -3 <= x < -2

f(x)= x when -2 <= x < 2

f(x)= -2x + 6 when 2 <= x < 3

f(x)= x - 3 when 3 <= x < 7

f(x)= -2x + 18 when 7 <= x < 8

f(x)= 2 when x >= 8

Create a function M-file, PieceZigZag, that accepts one or more values as input, evaluates the piecewise function at that number & returns this as output.

The function should accept an array as input for x.

Use a for loop to build the output array containing f(x). Preallocate this array.

Examples:

Explanation / Answer

%matlab code

function y = PieceZigZag(x)
l = length(x);
y = zeros(1,l);
  
for i=1:l
if x(i) < -3
y(i) = x(i)+3;
elseif x(i) < -2
y(i) = -2*x(i)-6;
elseif x(i) < 2
y(i) = x(i);
elseif x(i) < 3
y(i) = -2*x(i)+6;
elseif x(i) < 7
y(i) = x(i)-3;
elseif x(i) < 8
y(i) = -2*x(i)+18;
elseif x(i) >= 9
y(i) = 2;
else
disp('Invalid Input');
end
end
end

y = PieceZigZag(-10)
%output: y = -7

y = PieceZigZag([-10 10])
%output: y = -7 2