How do I get this function to accept one input argument, a vector representing the three coefficients of the quadratic in the order a, b, c?

2 ビュー (過去 30 日間)
function[quadRoots, disc] = Q1(coeff)
%function solves quadratic equation in the form ax^2 + bx + c = 0
a= coeff(1,1);
b= coeff(2,1);
c= coeff(3,1);
end
%finding the descriminant
disc = (b^2-4*a*c);
%roots
if disc>0
x1= ((-b+sqrt(disc))/(2*a));
x2= ((-b-sqrt(disc))/(2*a));
quadRoots= [x1, x2]
end
%no real roots
if disc<0
quadRoots = nan;
end
%one real root
if disc == 0
x1= ((-b+sqrt(disc))/(2*a));
disc= (b^2-(4*a*c));
quadRoots - x1;
end
end

採用された回答

Adam Danz
Adam Danz 2020 年 1 月 22 日
編集済み: Adam Danz 2020 年 1 月 22 日
You're on the right track but there's some cleaning up to do (I have only evaluated the syntax).
1) Q1_18035200 is a really bad function name. It looks like it could be a variable so if I were to see Q1_18035200(1:3) I would think you're indexing, not calling a function (it would also be a bad variable name). Also, function names should be descriptive.
2) Your current definitions of a, b, and c require that the user enter a column vector. It's generally a good idea for the code to be more flexible and to allow the user to enter a column or row vector. The lines below will accept either.
a= coeff(1);
b= coeff(2);
c= coeff(3);
3) The first end ends your function and should result in an error when calling your function. Remove it.
This statement is not inside any function.
(It follows the END that terminates the definition of the function "Q1_18035200".)
4) Make sure you're terminating lines with a semicolon to supress outputs (see the quadRoots line).
5) This line isn't doing anything
quadRoots - x1;
  2 件のコメント
Adam Danz
Adam Danz 2020 年 1 月 22 日
No problem. Feel free to continue the discussion if you've got more questions on this topic.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by