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 Kommentar

Stephen23
Stephen23 am 16 Nov. 2018
Bearbeitet: Stephen23 am 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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

madhan ravi
madhan ravi am 16 Nov. 2018
Bearbeitet: madhan ravi am 16 Nov. 2018

0 Stimmen

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')

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Tags

Gefragt:

am 16 Nov. 2018

Bearbeitet:

am 16 Nov. 2018

Community Treasure Hunt

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

Start Hunting!

Translated by