When I run this function, it generates a graph with only the x-value of -2, why wont it plot the whole vector?
1 view (last 30 days)
Show older comments
function g
x_min = -2;
x_max = 2;
x = x_min:20:x_max
if x < -pi
g = -1;
elseif x >= -pi && x <= pi
g = cos(x);
else
g = -1;
end
plot(x, g, '--og')
xlabel('Value of x')
ylabel('Value of g(x)')
title('Value of Piecewise function g(x)')
end
0 Comments
Accepted Answer
Cris LaPierre
on 2 Apr 2023
Because you specified a step size of 20, but min and max of -2 and 2. Since the colon operator stops once the next increment would be greater than the end value, and since -2+20 is >2, you only end up with your start value.
x = -2:20:2
2 Comments
Cris LaPierre
on 2 Apr 2023
x = linspace(-2,2,20)
You can learn more about creating vectors and arrays in Ch 4 of MATLAB Onramp, a free, self-paced tutorial that covers the basics of MATLAB.
More Answers (0)
See Also
Categories
Find more on Get Started with MATLAB 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!