How to graph a Piecewise function?
Afficher commentaires plus anciens
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?
Réponse acceptée
Plus de réponses (1)
Image Analyst
le 10 Mar 2015
This kind of construct does not work
if 0 <= Theta <= pi/2
You need to do it in two comparisons, like this
if (0 <= Theta) && (Theta <= pi/2)
Each one of those things in the parentheses will product a true or false result. If you AND them together, you will get what you tried to do.
2 commentaires
John D'Errico
le 10 Mar 2015
Modifié(e) : John D'Errico
le 10 Mar 2015
Note that Theta is a vector. if statements will still fail to produce the proper result if they are applied to a vector.
You will need to loop over those elements, or use another scheme to determine the location of each point.
Image Analyst
le 10 Mar 2015
Good point. I didn't notice that because of the bad formatting, which can be fixed after viewing this: http://www.mathworks.com/matlabcentral/answers/13205-tutorial-how-to-format-your-question-with-markup
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!