Search code examples
matlabplotmatlab-figure

Plotting solution for quadratic equation


This is my primer time using matlab especially plotting.

I try to plot the solutions for y = x^2 − x − 2 like in here

enter image description here

But I don't know how to model this plot in matlab (it makes sense because the solutions must be computed first) but shouldn't the shape of curve will remain the same.

I tried:

clc;
close all;

%y = x2 − x − 2
x = [-3:1:3];

y= x.^2 - x -2;
plot(y), grid on;

But the curve I got is totally different.


Solution

  • You're choosing wrong points for drawing the curve.
    The image that you showed above takes the values of x in the interval [-2,3]. Fixing this gives exactly the same curve as that of the one in the question.
    Also note that the minima of your function is at x=0.5. So, if x has equal number of values less than 0.5 and greater than 0.5, you will get the curve of the desired shape.

    Code:

    x = [-2:0.01:3];  %Choosing 0.01, because more the points, more the curve will be accurate
    y= x.^2 - x -2;
    plot(x,y), grid on;
    

    Output:

    output