This example shows several different methods
to calculate the roots of a polynomial.
-
Numeric Roots
-
Roots Using Substitution
-
Roots in a Specific Interval
-
Symbolic Roots
Numeric Roots
The roots
function calculates
the roots of a single-variable polynomial represented by a vector
of coefficients.
For example, create a vector to represent the polynomial x2−x−6,
then calculate the roots.
p = [1 -1 -6]; r = roots(p)
By convention, MATLAB® returns the roots in a column vector.
The poly
function converts
the roots back to polynomial coefficients. When operating on vectors, poly
and roots
are
inverse functions, such that poly(roots(p))
returns p
(up
to roundoff error, ordering, and scaling).
When operating on a matrix, the poly
function
computes the characteristic polynomial of the matrix. The roots of
the characteristic polynomial are the eigenvalues of the matrix. Therefore, roots(poly(A))
and eig(A)
return
the same answer (up to roundoff error, ordering, and scaling).
Roots Using Substitution
You can solve polynomial equations involving trigonometric functions by simplifying the equation using a substitution. The resulting polynomial of one variable no longer contains any trigonometric functions.
For example, find the values of θ that solve the equation
3cos2(θ)-sin(θ)+3=0.
Use the fact that cos2(θ)=1-sin2(θ) to express the equation entirely in terms of sine functions:
-3sin2(θ)-sin(θ)+6=0.
Use the substitution x=sin(θ) to express the equation as a simple polynomial equation:
-3×2-x+6=0.
Create a vector to represent the polynomial.
Find the roots of the polynomial.
To undo the substitution, use θ=sin-1(x). The asin
function calculates the inverse sine.
theta = 2×1 complex
-1.5708 + 1.0395i
1.5708 - 0.7028i
Verify that the elements in theta
are the values of θ that solve the original equation (within roundoff error).
f = @(Z) 3*cos(Z).^2 - sin(Z) + 3; f(theta)
ans = 2×1 complex
10-14 ×
-0.0888 + 0.0647i
0.2665 + 0.0399i
Roots in a Specific Interval
Use the fzero
function to find the roots of a polynomial in a specific interval. Among other uses, this method is suitable if you plot the polynomial and want to know the value of a particular root.
For example, create a function handle to represent the polynomial 3×7+4×6+2×5+4×4+x3+5×2.
p = @(x) 3*x.^7 + 4*x.^6 + 2*x.^5 + 4*x.^4 + x.^3 + 5*x.^2;
Plot the function over the interval [-2,1].
x = -2:0.1:1; plot(x,p(x)) ylim([-100 50]) grid on hold on
From the plot, the polynomial has a trivial root at 0
and another near -1.5
. Use fzero
to calculate and plot the root that is near -1.5
.
Symbolic Roots
If you have Symbolic Math Toolbox™, then there are additional
options for evaluating polynomials symbolically. One way is to use
the solve
(Symbolic Math Toolbox) function.
syms x
s = solve(x^2-x-6)
Another way is to use the factor
(Symbolic Math Toolbox) function
to factor the polynomial terms.
See Solve Algebraic Equations (Symbolic Math Toolbox) for more information.
See Also
roots
| poly
| eig
Related Topics
- Create and Evaluate Polynomials
- Roots of Scalar Functions
- Integrate and Differentiate Polynomials
Main Content
Syntax
Description
example
r = roots(
returnsp
)
the roots of the polynomial represented by p
as
a column vector. Input p
is a vector containing n+1
polynomial
coefficients, starting with the coefficient of xn.
A coefficient of 0
indicates an intermediate power
that is not present in the equation. For example, p = [3
represents the polynomial 3×2+2x−2.
2 -2]
The roots
function solves polynomial equations
of the form p1xn+…+pnx+pn+1=0.
Polynomial equations contain a single variable with nonnegative exponents.
Examples
collapse all
Roots of Quadratic Polynomial
Solve the equation 3×2-2x-4=0.
Create a vector to represent the polynomial, then find the roots.
p = [3 -2 -4]; r = roots(p)
Roots of Quartic Polynomial
Solve the equation x4-1=0.
Create a vector to represent the polynomial, then find the roots.
p = [1 0 0 0 -1]; r = roots(p)
r = 4×1 complex
-1.0000 + 0.0000i
0.0000 + 1.0000i
0.0000 - 1.0000i
1.0000 + 0.0000i
Input Arguments
collapse all
Polynomial coefficients, specified as a vector. For example,
the vector [1 0 1]
represents the polynomial x2+1,
and the vector [3.13 -2.21 5.99]
represents the
polynomial 3.13×2−2.21x+5.99.
For more information, see Create and Evaluate Polynomials.
Data Types: single
| double
Complex Number Support: Yes
Tips
-
Use the
poly
function
to obtain a polynomial from its roots:p = poly(r)
.
Thepoly
function is the inverse of theroots
function. -
Use the
fzero
function
to find the roots of nonlinear equations. While theroots
function
works only with polynomials, thefzero
function
is more broadly applicable to different types of equations.
Algorithms
The roots
function considers p
to
be a vector with n+1
elements representing the n
th
degree characteristic polynomial of an n
-by-n
matrix, A
.
The roots of the polynomial are calculated by computing the eigenvalues
of the companion matrix, A
.
A = diag(ones(n-1,1),-1); A(1,:) = -p(2:n+1)./p(1); r = eig(A)
The results produced are the exact eigenvalues of a matrix within
roundoff error of the companion matrix, A
. However,
this does not mean that they are the exact roots of a polynomial whose
coefficients are within roundoff error of those in p
.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
-
Output is variable-size and always complex.
-
Roots are not always in the same order as in MATLAB®.
-
Roots of poorly conditioned polynomials do not always match
MATLAB. -
See Variable-Sizing Restrictions for Code Generation of Toolbox Functions (MATLAB Coder).
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool
or accelerate code with Parallel Computing Toolbox™ ThreadPool
.
This function fully supports thread-based environments. For
more information, see Run MATLAB Functions in Thread-Based Environment.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
Usage notes and limitations:
-
The output
r
is always complex even if all the
imaginary parts are zero.
For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).
Version History
Introduced before R2006a
roots
Синтаксис
Описание
пример
r = roots(
возвращает корни полинома, представленного p
)p
как вектор-столбец. Введите p
вектор, содержащий n+1
полиномиальные коэффициенты, начиная с коэффициента xn. Коэффициент 0
указывает на промежуточную степень, которая не присутствует в уравнении. Например, p = [3 2 -2]
представляет полином 3×2+2x−2.
roots
функция решает полиномиальные уравнения формы p1xn+…+pnx+pn+1=0. Полиномиальные уравнения содержат одну переменную с неотрицательными экспонентами.
Примеры
свернуть все
Корни квадратичного многочлена
Решите уравнение 3×2-2x-4=0.
Создайте вектор, чтобы представлять полином, затем найти корни.
p = [3 -2 -4]; r = roots(p)
Корни биквадратного многочлена
Решите уравнение x4-1=0.
Создайте вектор, чтобы представлять полином, затем найти корни.
p = [1 0 0 0 -1]; r = roots(p)
r = 4×1 complex
-1.0000 + 0.0000i
0.0000 + 1.0000i
0.0000 - 1.0000i
1.0000 + 0.0000i
Входные параметры
свернуть все
Полиномиальные коэффициенты в виде вектора. Например, векторный [1 0 1]
представляет полином x2+1, и векторный [3.13 -2.21 5.99]
представляет полином 3.13×2−2.21x+5.99.
Для получения дополнительной информации смотрите, Создают и Оценивают Полиномы.
Типы данных: single
| double
Поддержка комплексного числа: Да
Советы
-
Используйте
poly
функция, чтобы получить полином из его корней:p = poly(r)
.poly
функция является инверсиейroots
функция. -
Используйте
fzero
функционируйте, чтобы найти корни нелинейных уравнений. В то время какroots
функция работает только с полиномами,fzero
функция более широко применима к различным типам уравнений.
Алгоритмы
roots
функция рассматривает p
быть вектором с n+1
элементы, представляющие n
полином характеристики степени th n
— n
матрица, A
. Корни полинома вычисляются путем вычисления собственных значений сопровождающей матрицы, A
.
A = diag(ones(n-1,1),-1); A(1,:) = -p(2:n+1)./p(1); r = eig(A)
Приведенными результатами являются точные собственные значения матрицы в ошибке округления сопровождающей матрицы, A
. Однако это не означает, что они — точные корни полинома, коэффициенты которого в ошибке округления тех в p
.
Расширенные возможности
Генерация кода C/C++
Генерация кода C и C++ с помощью MATLAB® Coder™.
Указания и ограничения по применению:
-
Выход является переменным размером, и всегда объединяйте.
-
Корни находятся не всегда в том же порядке как в MATLAB®.
-
Корни плохо обусловленных полиномов не всегда совпадают с MATLAB.
-
«Смотрите информацию о генерации кода функций Toolbox (MATLAB Coder) в разделе «»Ограничения переменных размеров»».».
Основанная на потоке среда
Запустите код в фоновом режиме с помощью MATLAB® backgroundPool
или ускорьте код с Parallel Computing Toolbox™ ThreadPool
.
Эта функция полностью поддерживает основанные на потоке среды. Для получения дополнительной информации смотрите функции MATLAB Запуска в Основанной на потоке Среде.
Массивы графического процессора
Ускорьте код путем работы графического процессора (GPU) с помощью Parallel Computing Toolbox™.
Указания и ограничения по применению:
-
Выход
r
является всегда комплексным, даже если все мнимые части являются нулем.
Для получения дополнительной информации смотрите функции MATLAB Запуска на графическом процессоре (Parallel Computing Toolbox).
Представлено до R2006a
- Получите корни многочлена с помощью функции
roots()
в MATLAB - Получите корни полинома с помощью функции
solve()
в MATLAB
Это руководство познакомит вас с тем, как найти корни многочлена с помощью функций roots()
и solve()
в MATLAB.
Получите корни многочлена с помощью функции roots()
в MATLAB
Если вы хотите найти корни многочлена, вы можете использовать функцию roots()
в MATLAB. Этот вход этой функции — вектор, который содержит коэффициенты полинома. Если в полиноме нет степени, то в качестве его коэффициента будет использоваться 0. Результатом этой функции является вектор-столбец, содержащий действительные и мнимые корни данного многочлена. Например, давайте найдем корни квадратного полинома: 2x ^ 2 — 3x + 6 = 0. Мы должны определить коэффициенты полинома, начиная с наивысшей степени, и если степень отсутствует, мы будем использовать 0 в качестве ее коэффициента. . См. Код ниже.
poly = [2 -3 6];
p_roots = roots(poly)
Выход:
p_roots =
0.7500 + 1.5612i
0.7500 - 1.5612i
В приведенном выше коде мы использовали только коэффициенты полинома, начиная с наибольшей степени. Вы можете изменить коэффициенты многочлена в соответствии с данным многочленом. Знаем, давайте найдем корни многочлена четвертой степени: 2x ^ 4 + 1 = 0. См. Код ниже.
poly = [2 0 0 0 1];
p_roots = roots(poly)
Выход:
p_roots =
-0.5946 + 0.5946i
-0.5946 - 0.5946i
0.5946 + 0.5946i
0.5946 - 0.5946i
Мы использовали три 0 между двумя полиномами в приведенном выше коде, потому что три степени отсутствуют. Проверьте эту ссылку для получения дополнительной информации о функции root()
.
Получите корни полинома с помощью функции solve()
в MATLAB
Если вы хотите найти корни многочлена, вы можете использовать функцию resolve()
в MATLAB. Этот вход этой функции является полиномом. Результатом этой функции является вектор-столбец, содержащий действительные и мнимые корни данного многочлена. Например, давайте найдем корни квадратного многочлена: 2x ^ 2 — 3x + 6 = 0. Нам нужно определить многочлен. См. Код ниже.
syms x
poly = 2*x^2 -3*x +6 == 0;
p_roots = solve(poly,x)
p_roots = vpa(p_roots,2)
Выход:
p_roots =
0.75 - 1.6i
0.75 + 1.6i
В приведенном выше коде мы определили весь многочлен и использовали функцию vpa()
, чтобы изменить точность результата. Вы можете изменить полином в соответствии с заданным полиномом и точностью в соответствии с вашими требованиями. Знаем, давайте найдем корни многочлена четвертой степени: 2x ^ 4 + 1 = 0. См. Код ниже.
syms x
poly = 2*x^4 +1 == 0;
p_roots = solve(poly,x);
p_roots = vpa(p_roots,2)
Выход:
p_roots =
- 0.59 - 0.59i
- 0.59 + 0.59i
0.59 - 0.59i
0.59 + 0.59i
В приведенном выше коде мы определили весь многочлен и использовали функцию vpa()
для изменения точности результата. Вы можете изменить полином в соответствии с заданным полиномом и точностью в соответствии с вашими требованиями.
Main Content
Curve fitting, roots, partial fraction expansions
Polynomials are equations of a single variable with nonnegative integer exponents.
MATLAB® represents polynomials with numeric vectors containing the polynomial
coefficients ordered by descending power. For example, [1 -4 4]
corresponds
to x2 — 4x +
4. For more information, see Create and Evaluate Polynomials.
Functions
poly |
Polynomial with specified roots or characteristic polynomial |
polyeig |
Polynomial eigenvalue problem |
polyfit |
Polynomial curve fitting |
residue |
Partial fraction expansion (partial fraction decomposition) |
roots |
Polynomial roots |
polyval |
Polynomial evaluation |
polyvalm |
Matrix polynomial evaluation |
conv |
Convolution and polynomial multiplication |
deconv |
Deconvolution and polynomial division |
polyint |
Polynomial integration |
polyder |
Polynomial differentiation |
Topics
- Create and Evaluate Polynomials
This example shows how to represent a polynomial as a vector in MATLAB® and evaluate the polynomial at points of interest.
- Roots of Polynomials
Calculate polynomial roots numerically, graphically,
or symbolically. - Integrate and Differentiate Polynomials
This example shows how to use the
polyint
andpolyder
functions to analytically integrate or differentiate any polynomial represented by a vector of coefficients. - Polynomial Curve Fitting
This example shows how to fit a polynomial curve to a set of data points using the
polyfit
function. - Programmatic Fitting
There are many functions in MATLAB that are useful for data fitting.
Featured Examples