find solutions of cubic equation in matlab

To find the solutions of cubic equation in Matlab, we can use the roots function. However, we need to convert the equation to a specific form before that. Here's how you can do that:

  1. Start by defining the coefficients of the cubic equation in the form ax^3 + bx^2 + cx + d = 0.
  2. Next, define a new variable w as (-b + sqrt(b^2 - 4ac + 3*a*(-c + sqrt(c^2 - (b^2/(3*a))^3))))^(1/3).
  3. Define two more variables s and t as (2*w^2 - b)/(3*a) and (-w^2 - b + sqrt(3)*i*w + 2*sqrt(3)*sqrt(w^2 - c))/(3*a).
  4. Finally, compute the roots using the following formula: x = s + t + (-1/3)*b/a.

Here's the complete code that implements this method:

main.m
% Define the coefficients of the cubic equation
a = 1;
b = 2;
c = 3;
d = 4;

% Compute the solutions of the cubic equation
w = (-b + sqrt(b^2 - 4*a*c + 3*a*(-c + sqrt(c^2 - (b^2/(3*a))^3))))^(1/3);
s = (2*w^2 - b)/(3*a);
t = (-w^2 - b + sqrt(3)*i*w + 2*sqrt(3)*sqrt(w^2 - c))/(3*a);
x = s + t + (-1/3)*b/a;

disp(x); % Print the solutions
339 chars
14 lines

Note that this method only works for real coefficients. If your coefficients are complex, you will need to use the sym function to convert them to symbolic form and then use the solve function instead of roots.

gistlibby LogSnag