how to write a function for quadratic equation?
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I wrote this into matlab but it doesn't work where a=0, can someone explain why?
how can find x1, x2 where a=0?
function [x1,x2] = f (a,b,c)
d=b^2-4*a*c;
if d>=0
x1=(-b-sqrt(d))/(2*a);
x2=(-b+sqrt(d))/(2*a);
plot(x1,0,'rx',x2,0,'rx')
hold on
fplot(@(x) a*x.^2+b*x+c)
hold off
else
[x1,x2]=deal([])
end
end
1 comentario
Dyuman Joshi
el 24 de Sept. de 2022
If a=0, then it's a straight line, it will only intersect the x-axis once.
Also, if a=0 then the expressions
x1=(-b-sqrt(d))/(2*a);
x2=(-b+sqrt(d))/(2*a);
will become not defined.
You have to write a special condition for a=0, according to what you expect.
Respuestas (1)
Hiro Yoshino
el 24 de Sept. de 2022
You can check the arguments before evaluating your statements this way:
[x1,x2] = f(1,-2,1)
[x1,x2] = f(0,-2,1)
function [x1,x2] = f(a,b,c)
arguments
a (1,1) {mustBeNonzero}
b (1,1) {mustBeReal}
c (1,1) {mustBeReal}
end
d=b^2-4*a*c;
if d>=0
x1=(-b-sqrt(d))/(2*a);
x2=(-b+sqrt(d))/(2*a);
plot(x1,0,'rx',x2,0,'rx')
hold on
fplot(@(x) a*x.^2+b*x+c)
hold off
else
[x1,x2]=deal([])
end
end
For further detail, go and visit https://www.mathworks.com/help/matlab/matlab_prog/function-argument-validation-1.html
Ver también
Categorías
Más información sobre Polynomials en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!