need help Writing a function that returns roots of a quadratic
3 ビュー (過去 30 日間)
古いコメントを表示
This is my plan on how to write it (don't have software at my disposal currently). I am learning matlab so understand there may be quite a few problems.
Function [x]=myquad(a,b,c)
x=[r1 r2];
d=sqrt((b.^2)-4.*a.*c)
if a==0 & b>0
r1=-c/b;
elseif a==0 & b==0
r1=0;
elseif a~=0 & d==0
r1=-b./(2.*a);r2=r1;
elseif a~=0 & d>0
r1=(-b+d)./2a; r2=(-b+d)./2.*a;
elseif a~=0 & d<0
r1=(-b+d.*i)/2a; r2=(-b-d.*i)./2.*a;
end
end
I need to follow this algorithm for an assignment.
THANKS!
0 件のコメント
採用された回答
Walter Roberson
2013 年 2 月 17 日
編集済み: Walter Roberson
2013 年 2 月 17 日
Your first two cases do not appear to set r2 to anything.
your a=0 b=0 case is wrong
Your "di" should probably be "d*i"
6 件のコメント
その他の回答 (2 件)
Azzi Abdelmalek
2013 年 2 月 17 日
There are some mistakes
if a==0 %instead of if a=0
elseif % instead of ifelse
1 件のコメント
Walter Roberson
2013 年 2 月 17 日
Multiple assignment is not permitted. r1=r2=VALUE is not allowed. Use r1=VALUE; r2=r1
Image Analyst
2013 年 2 月 18 日
Why do you need all those "if"s at all? Why not just do
function [r1 r2]=myquad(a,b,c)
d = sqrt((b^2)-4*a*c); % Can be complex with no problem.
r1=(-b-d)/(2*a);
r2=(-b+d)/(2*a);
MATLAB handles complex numbers and infinite numbers with no problem, so you don't need special if statements to do it manually.
参考
カテゴリ
Help Center および File Exchange で Get Started with Optimization Toolbox についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!