for loop question help

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 Comment

Stephen23
Stephen23 on 16 Nov 2018
Edited: Stephen23 on 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.

Sign in to comment.

Answers (1)

madhan ravi
madhan ravi on 16 Nov 2018
Edited: madhan ravi on 16 Nov 2018
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')

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Asked:

on 16 Nov 2018

Edited:

on 16 Nov 2018

Community Treasure Hunt

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

Start Hunting!