What is the standard code for solving any cubic equation
Show older comments
I have been asked to submit the standard code for solving any cubic equation but I do not know?need help ASAP .
1 Comment
Roger Stafford
on 7 May 2013
Edited: Walter Roberson
on 28 Jan 2025
See this article:
Answers (3)
Matt J
on 7 May 2013
0 votes
See the ROOTS command.
% Simple Cubic Equation Solver
clc;
clear;
% Input coefficients for the cubic equation ax^3 + bx^2 + cx + d = 0
a = input('Enter coefficient a (for x^3): ');
b = input('Enter coefficient b (for x^2): ');
c = input('Enter coefficient c (for x): ');
d = input('Enter constant d: ');
% Check if it's a valid cubic equation
if a == 0
disp('This is not a cubic equation.');
else
% Define polynomial coefficients and solve
coefficients = [a b c d];
roots_cubic = roots(coefficients);
% Display the roots
disp('The roots of the cubic equation are:');
disp(roots_cubic);
end
syms a b c d x
R = solve(a*x^3 + b*x^2 + c*x + d == 0, x, 'maxdegree', 3);
matlabFunction(R, 'file', 'CubicSolver.m', 'vars', {a b c d} )
dbtype CubicSolver.m
Now CubicSolver.m exists in your current directory, and can be called with four parameters that are compatible in size (but best if they are scalars or row vectors.)
Categories
Find more on Polynomials in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!