MATLAB Answers

Getting incorrect plot – curve does not cross the x axis correctly

3 views (last 30 days)
Milan Hrstka
Milan Hrstka on 29 Apr 2021
Commented: Milan Hrstka on 29 Apr 2021
Hello,
I'm trying to plot a quadratic equation with highlighted roots and I am facing a problem – my curve does not cross x axis correctly.
For example:
y = 2x^2 - 4x, => roots are x1 = 2, x2 = 0 and I get this graph:
So the blue curve should cross the red points but does not. I dont know why.
My code for plotting this is like this:
x = [min(x1, x2)-5:0.1:max(x1, x2)+5];
y = (koef_a*x).^2 + koef_b*x + koef_c;
plot(x, y, 'b'), grid on, xlabel('x'), ylabel('y');
ax = gca; % Get handles to axis.
ax.YAxisLocation = 'origin';
ax.XAxisLocation = 'origin';
hold on;
plot(x1, 0, 'o', 'MarkerSize', 5, 'MarkerFaceColor', 'r', 'MarkerEdgeColor', 'r');
plot(x2, 0, 'o', 'MarkerSize', 5, 'MarkerFaceColor', 'r', 'MarkerEdgeColor', 'r');
hold off;
I would be very grateful for any help. Thanks

Answers (2)

Star Strider
Star Strider on 29 Apr 2021
The roots are [0 2], so use those with the poly function:
rts = [0 2];
coefs = poly(rts)
coefs = 1×3
1 -2 0
figure
fplot(@(x) x.^2 - 2.*x, [-5 5])
hold on
scatter(rts, [0 0], 'r', 'filled')
hold off
grid
set(gca,'XTick',-5:5)

VBBV
VBBV on 29 Apr 2021
Edited: VBBV on 29 Apr 2021
%f true
x = [-5:0.1:+5];
y = 2*(x).^2 - 4*x ;
plot(x, y, 'b'), grid on, xlabel('x'), ylabel('y');
ax = gca; % Get handles to axis.
ax.YAxisLocation = 'origin';
ax.XAxisLocation = 'origin';
hold on;RTS = [0 2];
scatter(RTS,[0 0],'r','filled')
  3 Comments
Milan Hrstka
Milan Hrstka on 29 Apr 2021
Sure but look, i used your help and my code looks like this now:
x = [min(x1, x2)-5:0.1:max(x1, x2)+5];
y = (koef_a*x).^2 + koef_b*x + koef_c;
plot(x, y, 'b'), grid on, xlabel('x'), ylabel('y');
ax = gca; % Get handles to axis.
ax.YAxisLocation = 'origin';
ax.XAxisLocation = 'origin';
hold on; RTS = [x1 x2];
scatter(RTS, [0 0], 'r', 'filled');
hold off;
x1 and x2 are the roots, koef_a, koef_b, koef_c are coefficients
And for y = x^2 - 2x its fine:
But for example using y = 5x^2 + 3x - 6 is not fine .. so i don't get it

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by