How to write an quadratic.m function

29 views (last 30 days)
Sofie Önnemar
Sofie Önnemar on 1 Sep 2022
Answered: Steven Lord on 1 Sep 2022
I have the equation: ax2 + bx + c = 0.
- Equation does not have real roots if d= b2 4ac < 0.
- Equation has two real roots x1 = (−b+sqrt(d))/(2a) and x2 = (−b−sqrt(d))/(2a) if d> 0.
- Equation has one (repeated) real root x = (−b)/(2a) if d= 0.
Write a Matlab function quadratic.m that accepts the values of coefficients a,
b, c as inputs and calculates the real roots of quadratic equation.
My question is how do I write the quadratic.m function before I do the if-statement?
This is what I got so far:
function [x1,x2] = QuadraticEquation(a,b,c)
if b^2-4*a*c<0
root=['No Real Root'];
elseif b^2-4*a*c==0
%the equation has one repeated real root
root(1)=-b/(2*a);
else
root(2)=(-b+sqrt(b^2-4*a*c))/(2*a);
root(3)=(-b-sqrt(b^2-4*a*c))/(2*a);
end
end
[SL: formatted code as code]

Answers (1)

Steven Lord
Steven Lord on 1 Sep 2022
I assume you've saved this in a file named QuadraticEquation.m. If so you just need to rename the file to quadratic.m and ideally change the name of the function inside the new quadratic.m to quadratic instead of QuadraticEquation. Best practice is for the name of the file and the name of the main function in that file to match; if they don't, you will need to call the function using the name of the file.
But you have another problem: the variables you've defined (or not defined) in your function. Nowhere in your code do you define the variables x1 and x2 that the function declaration line states should be returned from the function. You also define a variable named root but you never use the values you assign to it. In your else statement you also assign to the second and third elements of root, which will automatically make the first element equal to 0.
Another portion of your code that I'm not sure will satisfy your assignment, are you sure that your assignment wants you to return the text 'No Real Root' in the case where there are no real roots? I'd probably return an empty array (either zeros(1, 0) or [] depending on if the caller requires the output to be a vector or not) for that case.

Community Treasure Hunt

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

Start Hunting!