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?

4 views (last 30 days)
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

Accepted Answer

Adam Danz
Adam Danz on 22 Jan 2020
Edited: Adam Danz on 22 Jan 2020
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;

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!