how to write a function for quadratic equation?

조회 수: 18 (최근 30일)
jun
jun 2022년 9월 24일
댓글: jun 2022년 9월 24일
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
Dyuman Joshi
Dyuman Joshi 2022년 9월 24일
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.

댓글을 달려면 로그인하십시오.

답변 (1개)

Hiro Yoshino
Hiro Yoshino 2022년 9월 24일
You can check the arguments before evaluating your statements this way:
[x1,x2] = f(1,-2,1)
x1 = 1
x2 = 1
[x1,x2] = f(0,-2,1)
Error using solution>f
Invalid argument at position 1. Value must not be zero.
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
  댓글 수: 1
jun
jun 2022년 9월 24일
it semms only a=non-zero case by argument state, did i understnad correctey?
If a=0 and non-a=/=0 situations need to be written separately as without setting arguments,
Where and how to add conditions for a=0 and a=/=0 situations?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Computational Geometry에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by