Use a ‘for loop’ to compute and plot the following function over the interval -2pi<= x <= 2pi:
for x < -pi g(x)=cos(x)+2
for x => -pi and x<=pi g(x)=2
for x>pi g(x)=cos(x)-2
Plot g versus x for x from -2pi to +2pi (x on the horizontal axis, g on the vertical). All the three functions should be plotted in one diagram (one waveform).
Use at least 100 points in your x vector so you get a smooth curve. Label your graph.
I need help with this one also.
thanks

1 commentaire

Stephen23
Stephen23 le 16 Nov 2018
Modifié(e) : Stephen23 le 16 Nov 2018
@Terrell Curley: I notice you are just getting madhan ravi to do all of your homework for you. Hopefully you are aware that:
  1. you will learn more by trying yourself first.
  2. using madhan ravi's code without attribution is plagiarism.
  3. your professor/tutor can find this website just as easily as you can.

Connectez-vous pour commenter.

Réponses (1)

madhan ravi
madhan ravi le 16 Nov 2018
Modifié(e) : madhan ravi le 16 Nov 2018

0 votes

Read about logical indexing and labels
without loop (efficient)
x=linspace(-2*pi,2*pi);
g(x<pi)=cos(x(x<-pi))+2;
idx = ( x >= -pi ) & ( x<=pi ) ;
g(idx)=2;
g(x>pi)=cos(x(x>pi))-2;
plot(x,g,'r')
with loop (inefficient)
x=linspace(-2*pi,2*pi);
g=zeros(1,numel(x)); %pre-allocation for speed and efficiency
for i =1:numel(x)
if x(i)<-pi;
g(i)=cos(x(i))+2;
elseif x(i) >= -pi && x(i)<=pi ;
g(i)=2;
else x(i)>pi ;
g(i)=cos(x(i))-2;
end
end
plot(x,g,'r')

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by