how to write a function for quadratic equation?

4 次查看(过去 30 天)
I wrote this into matlab but it doesn't work where express x1, x2, it express only one sol in d>=0 but ploting is work in d>=0. and it's error in d<0
why it doen't work and how to fix it?
function [x1,x2] = f(a,b,c)
if a==0
x1=-c/b;
x2=-c/b;
plot(x1,0,'gx',x2,0,'gx')
hold on
fplot(@(x) a*x.^2+b*x+c)
hold off
end
d=b^2-4*a*c;
if (d>=0)&&(~(a==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
elseif a==0
x1=-c/b;
x2=-c/b;
plot(x1,0,'gx',x2,0,'gx')
hold on
fplot(@(x) a*x.^2+b*x+c)
hold off
else
[x1 x2]=[]
end
  4 个评论
Dyuman Joshi
Dyuman Joshi 2022-9-25
Do you want to return empty values for if any/both of the two conditions - a==0 , d<0?
jun
jun 2022-9-25
i want d<0 => empty value return
but a=0&d<0 => x1=x2=-c/b return that i want

请先登录,再进行评论。

采纳的回答

VBBV
VBBV 2022-9-25
if (d>=0) & (~(a==0))
use binary operator &
  11 个评论
jun
jun 2022-9-26
Are you right about 'a==0'? If 'a=0', an error like this is displayed
Dyuman Joshi
Dyuman Joshi 2022-9-26
Let me highlight it. See the green parts, both are same.
I would suggest you to remove the top one and edit last else as
elseif d<0
function [x1,x2] = f(a,b,c)
%{
if a==0
x1=-c/b;
x2=-c/b;
plot(x1,0,'gx',x2,0,'gx')
hold on
fplot(@(x) a*x.^2+b*x+c)
hold off
end
%}
d=b^2-4*a*c
if (d>=0)&&(~(a==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
%{
elseif a==0
x1=-c/b;
x2=-c/b;
plot(x1,0,'gx',x2,0,'gx')
hold on
fplot(@(x) a*x.^2+b*x+c)
hold off
%}
else
x1 = [];
x2 = [];
end
end

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Timing and presenting 2D and 3D stimuli 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by