# Octave Programming Tutorial/Polynomials

In Octave, a polynomial is represented by its coefficients (arranged in descending order). For example, the vector

octave:1> p = [-2, -1, 0, 1, 2];

represents the polynomial

You can check this by displaying the polynomial with the function `polyout`

.

octave:2> polyout(p, 'x') -2*x^4 - 1*x^3 + 0*x^2 + 1*x^1 + 2

The function displays the polynomial in the variable specified (`x`

in this case). Note that the `^`

means *raised to the power of* much like the Octave operator.

## FunctionsEdit

- Evaluating a polynomial:

y = polyval(p, x)

This returns . If *x* is a vector or matrix, the polynomial is evaluated at each of the elements of *x*.

- Multiplication:

r = conv(p, q)

Here, `p`

and `q`

are vectors containing the coefficients of two polynomials and the result, `r`

, will contain the coefficients of their product.

(As an aside, the reason this function is called `conv`

is that we use vector convolution to do polynomial multiplication.)

- Division:

[b, r] = deconv(y, a)

This returns the coefficients of the polynomials *b* and *r* such that

So, `b`

contains the coefficients of the quotient and `r`

the coefficients of the remainder of *y* and *a* .

- Root finding:

roots(p)

This returns a vector containing all the roots of the polynomial with coefficients in `p`

.

- Derivative:

q = polyder(p)

This returns the coefficients of the derivative of the polynomial whose coefficients are given by vector `p`

.

- Integration:

q = polyint(p)

This returns the coefficients of the integral of the polynomial whose coefficients are represented by the vector `p`

. The constant of integration is set to 0.

- Data fitting:

p = polyfit(x, y, n)

This returns the coefficients of a polynomial of degree that best fits the data in the least squares sense.

### Warning: Adding polynomialsEdit

Since polynomials are represented by vectors of their coefficients, adding polynomials is not straightforward in Octave. For example, we define the polynomials and .

octave:1> p = [1, 0, -1]; octave:2> q = [1, 1];

If we try to add them, we get

octave:3> p + q error: operator +: nonconformant arguments (op1 is 1x3, op2 is 1x2) error: evaluating binary operator `+' near line 22, column 3

This happens because Octave is trying to add two vectors (`p`

and `q`

) of different lengths. This operation is not defined. To work around this, you have to add some leading zeroes to `q`

.

octave:4> q = [0, 1, 1];

Note that adding leading zeroes does not change the polynomial. Next, we add

octave:5> p + q ans = 1 1 0 octave:6> polyout(ans, 'x') 1*x^2 + 1*x^1 + 0

Return to the Octave Programming tutorial index