In: Mechanical Engineering
Use a for loop to plot the function given in Problem 16 over the interval -2 ≤ x ≤ 6. Properly label the plot. The variable y represents height in kilometers, and the variable x represents time in seconds.
Program plan:
• To write a matlab code that using for loop to plot the piece wise function in the conditional statement.
Program:
%**********************************************************
%A matlab code to plot the piece wise function using the
%for loop for the given range of ‘x’.
%**********************************************************
%Program Code
%Declaration of the array
x=[-2:0.1:6];
for (i=1:length(x)) %Initialization of for loop
if (x(i)<-1) %Conditional statement
%Computes the value
y(i)=exp(x(i)+1);
elseif (x(i)>=-1)&(x(i)<5) %Conditional statement
%computes the value
y(i)=2+cos(pi*x(i));
else %Default statement
%Computes the value
y(i)=10*(x(i)-5)+1;
end %End of conditional statement
end %End of for loop
%Plotting the piece wise function
plot (x,y);
%Assigns text to x-axis
xlabel(\'Time in seconds\');
%Assigns text to y-axis
ylabel(\'Height in kilometers\');
Output: