필터 지우기
필터 지우기

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

조회 수: 3 (최근 30일)
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.

채택된 답변

John D'Errico
John D'Errico 2021년 5월 30일
편집: John D'Errico 2021년 5월 30일
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
John D'Errico
John D'Errico 2021년 5월 30일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Quadratic Programming and Cone Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by