# how to write a function for quadratic equation

5 views (last 30 days)
Alisha Mistry on 6 Dec 2019
Commented: Image Analyst on 7 Dec 2019
I wrote this into matlab but it doesn't work, can someone explain why?
d=b^2-4*a*c;
if d>=0
disp ('two roots exist')
x1=(-b-sqrt(d))/2*a
x2=(-b+sqrt(d))/2*a
plot(x1,0,'rx',x2,0,'rx')
hold on
x=-10:10
y=a*x.^2+b*x+c
plot(x,y)
hold off
else
disp ('no real roots’)
end

Matt J on 7 Dec 2019
First explain to us why you think it doesn't work.
Alisha Mistry on 7 Dec 2019
It keeps saying the variables a,b,c aren't defined but i put them into a script as a function so why does it still say that message?
Image Analyst on 7 Dec 2019
You need to pass in something. You can't just click the green Run triangle on the toolbar. See Matt J's Answer below.

Matt J on 7 Dec 2019
Edited: Matt J on 7 Dec 2019
d=b^2-4*a*c;
if d>=0
disp ('real roots exist')
x1=(-b-sqrt(d))/(2*a); %<---------- brackets in denominator
x2=(-b+sqrt(d))/(2*a); %<---------- brackets in denominator
plot(x1,0,'rx',x2,0,'rx')
hold on
fplot(@(x) a*x.^2+b*x+c) %<---------- fplot is more convenient here
hold off
else
disp ('no real roots') %<---------- missing quote
[x1,x2]=deal([]) %<---------- missing default assignment
end
end