How to calculate roots for multiple polynomial equations simultaneously i.e. without iterating over them one by one

6 vues (au cours des 30 derniers jours)
Actually I have a bunch of quadratic equations(around 1 million equations!!) which I need to solve. I made a matrix of 1 million rows with each row is a vector containing coeff(s) for x^2, x^1 & x^0. i named this matrix M and wrote following code:
answers = zeros(1000000,2);
for i=1:1:length(answers)
answers(i,:) = roots(M(i,:));
end
I was wondering if there's a way we can calculate roots simultaneously for every polynomial equation without iterating over them one by one.

Réponse acceptée

John D'Errico
John D'Errico le 30 Mai 2021
Modifié(e) : John D'Errico le 30 Mai 2021
In fact, the simple answer is YES. It is trivial. No loop required.
You have a set of QUADRATIC EQUATIONS!!!!!! Surely you learned the quadratic formula for the roots of a quadratic equation?
tic
N = 1e6;
coef = rand(N,3);
D = sqrt(coef(:,2).^2 - 4*coef(:,1).*coef(:,3));
R = [(-coef(:,2) + D)./(2*coef(:,1)), (-coef(:,2) - D)./(2*coef(:,1))];
toc
Elapsed time is 0.115124 seconds.
size(R)
ans =
1000000 2
One million sets of roots, computed in around 1/10 of a second. Since my coefficients are randomly generated, many of those roots will be complex. As a test to verify it worked...
coef(1,:)
ans =
0.562209637790579 0.0918349300613903 0.952524012642822
R(1,:)
ans =
-0.0816732086115523 + 1.29906892840699i -0.0816732086115523 - 1.29906892840699i
roots(coef(1,:))
ans =
-0.0816732086115523 + 1.29906892840699i
-0.0816732086115523 - 1.29906892840699i
Hopefully your quadratics will be better behaved, and have real roots.
  2 commentaires
Earth Sugandhi
Earth Sugandhi le 30 Mai 2021
Thanks man!! this formula had just sliped off my mind
John D'Errico
John D'Errico le 30 Mai 2021
Some years ago, we realized we needed to do the same thing for zillions of cubic polynomials. So we wrote up the cubic formula, fully vectorized. Worked nicely.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Quadratic Programming and Cone Programming dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by