MATLAB: How to graph a Piecewise function

basichomeworkloopsMATLABplot

I need to graph a piecewise function in terms of theta for a Homework assignment.
I must first create a 100 element vector for the values of theta between 0 and 2*pi. After that I must use a loop and a conditional statement to plot the graph. Here is what I have so far:
Theta= 0:(2*pi)/100:2*pi; %the vector lists 100 elements(0 < Theta < 2Pi)
if (0 <= Theta) && (Theta <= pi/2)
%0<= Theta<= pi/2
Eq1= 6*(2*Theta - .5*sin(2*Theta))/pi
elseif (pi/2 <= Theta) && (Theta <= 2*pi/3)
%pi/2 <= Theta <= 2*pi/3
Eq2= 6
elseif (2*pi/3 <= Theta) && (Theta <= 4*pi/3)
%2*pi/3 <= Theta <= 4*pi/3
Eq3=7.5 - (1 - .5* cos(1.5* (Theta - (2*pi/3))))
elseif (4*pi/3 <= Theta) && (Theta <= 3*pi/2)
%4*pi/3 <= Theta <= 3*pi/2
Eq4= 3
elseif (3*pi/2 <= Theta) && (Theta <= 7*pi/4)
%3*pi/2<=Theta<=7*pi/4
Eq5= 3 - 1.5*((Theta - 3*(pi/2))/(pi/4))^2
elseif (7*pi/4 <= Theta) && (Theta <= 2*pi)
%7*pi/4 <= Theta <= 2*pi
Eq6= 1.5*(1 - ((Theta - 7*(pi/4/(pi/4)))^2
end
figure
plot(Theta, Eq1, Theta,Eq2,Theta,Eq3,Theta,Eq4,Theta,Eq5)
Everything is coming out jacked up, or not coming up at all… Please help! I know that I should place a loop, but where would it go?

Best Answer

%Theta= 0:(2*pi)/100:2*pi; %the vector lists 100 elemants between 0 and 2Pi
% Actually these are 101 elements;
% use
Theta = linspace(0, 2*pi, 100);
F = nan(size(Theta));
% logical indexing
ind = 0 <= Theta & Theta <= pi/2;
F(ind) = 6*(2*Theta(ind) - .5*sin(2*Theta(ind)))/pi;
% just one value, no ind variable necessary
F(pi/2 <= Theta & Theta <= 2*pi/3) = 6;
ind = 2*pi/3 <= Theta & Theta <= 4*pi/3;
F(ind) = 7.5 - (1 - 0.5* cos(1.5* (Theta(ind) - (2*pi/3))));
F(4*pi/3 <= Theta & Theta <= 3*pi/2) = 3;
ind = 3*pi/2 <= Theta & Theta <= 7*pi/4;
% use .^ to work on the whole vector
F(ind) = 3 - 1.5*((Theta(ind) - 3*(pi/2))/(pi/4)).^2;
ind = 7*pi/4 <= Theta & Theta <= 2*pi;
% some ) were missing, I added them at the end;
% PLEASE CHECK IF THIS IS THE RIGHT FUNCTION!!!
F(ind) = 1.5*(1 - ((Theta(ind) - 7*(pi/4/(pi/4))))).^2;
plot(Theta, F)