# 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

${\displaystyle -2x^{4}-x^{3}+x+2.}$

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.

## Functions

• Evaluating a polynomial:
```y = polyval(p, x)
```

This returns ${\displaystyle p(x)}$. 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

${\displaystyle y=ab+r.}$

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 ${\displaystyle p(x)}$ of degree ${\displaystyle n}$ that best fits the data ${\displaystyle (x_{i},y_{i})}$ in the least squares sense.

Since polynomials are represented by vectors of their coefficients, adding polynomials is not straightforward in Octave. For example, we define the polynomials ${\displaystyle p(x)=x^{2}-1}$ and ${\displaystyle q(x)=x+1}$.

```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];
```

```octave:5> p + q