how to write a function for quadratic equation

17 ビュー (過去 30 日間)
Alisha Mistry
Alisha Mistry 2019 年 12 月 6 日
コメント済み: Steven Lord 2024 年 7 月 13 日
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
  2 件のコメント
Grady
Grady 2024 年 7 月 12 日
This code will not work for me I am using 2024a.
Steven Lord
Steven Lord 2024 年 7 月 13 日
What does "will not work" mean in this context?
  • Do you receive warning and/or error messages? If so the full and exact text of those messages (all the text displayed in orange and/or red in the Command Window) may be useful in determining what's going on and how to avoid the warning and/or error.
  • Does it do something different than what you expected? If so, what did it do and what did you expect it to do?
  • Did MATLAB crash? If so please send the crash log file (with a description of what you were running or doing in MATLAB when the crash occured) to Technical Support so we can investigate.
Show us how you tried to use this code as well.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by