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

Accepted Answer

Cris LaPierre
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
x = -2
  2 Comments
Cris LaPierre
Cris LaPierre on 2 Apr 2023
If you want to specify the number of steps, use linspace.
x = linspace(-2,2,20)
x = 1×20
-2.0000 -1.7895 -1.5789 -1.3684 -1.1579 -0.9474 -0.7368 -0.5263 -0.3158 -0.1053 0.1053 0.3158 0.5263 0.7368 0.9474 1.1579 1.3684 1.5789 1.7895 2.0000
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!