for loop question help
Show older comments
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
@Terrell Curley: I notice you are just getting madhan ravi to do all of your homework for you. Hopefully you are aware that:
- you will learn more by trying yourself first.
- using madhan ravi's code without attribution is plagiarism.
- your professor/tutor can find this website just as easily as you can.
Answers (1)
madhan ravi
on 16 Nov 2018
Edited: madhan ravi
on 16 Nov 2018
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
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!