MATLAB: How to plot this Function in MATLAB

plotplotting

I need help plotting a signal f(x) in matlab. The signal is defined as:
f(x) =
{ (x+1)/2 , if -1 <= x < 1
{ 1 , if 1 <= x < 2
{ 0 , else
I cant figure out how to plot f(x) or f(x+1) Any help would be greatly appreciated.
P.S The range of x is from -4:4

Best Answer

I would make a function of it:
function y = custom_function(x)
% y = custom_function(x)
y = zeros(size(x)); %make y as big as x and fill it with zeros
first_situation = x >= -1 && x < 1;
second_situation = x >= 1 && x < 2;
y(first_situation) = (x(first_situation) + 1) / 2;
y(second_situation) = 1;
% the remainder of the values was already set to zero
end
to plot this function you would use:
x = -4:4; % set x from -4 to 4
y = custom_function(x);
plot(x,y)
or to plot x+1
x_2 = (-4:4)+1; % set x from -3 to 5
y_2 = custom_function(x_2);
plot(x_2,y_2)