how to write a function for quadratic equation

조회 수: 162 (최근 30일)
Alisha Mistry
Alisha Mistry 2019년 12월 6일
댓글: Image Analyst 2019년 12월 7일
I wrote this into matlab but it doesn't work, can someone explain why?
function [x1,x2] = QuadraticEquation (a,b,c)
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
  댓글 수: 3
Alisha Mistry
Alisha Mistry 2019년 12월 7일
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
Image Analyst 2019년 12월 7일
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
Matt J 2019년 12월 7일
편집: Matt J 2019년 12월 7일
[x1,x2] = QuadraticEquation (1,-2,0)
function [x1,x2] = QuadraticEquation (a,b,c)
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by