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 $$-2x^4 - x^3 + x + 2.$$ You can check this by displaying the polynomial with the function. 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 ( in this case). Note that the  means raised to the power of much like the Octave operator.

Functions
y = polyval(p, x) This returns $$p(x)$$. If x is a vector or matrix, the polynomial is evaluated at each of the elements of x.
 * Evaluating a polynomial:

r = conv(p, q) Here,  and   are vectors containing the coefficients of two polynomials and the result, , will contain the coefficients of their product.
 * Multiplication:

(As an aside, the reason this function is called  is that we use vector convolution to do polynomial multiplication.)

[b, r] = deconv(y, a) This returns the coefficients of the polynomials b and r such that $$y = ab + r.$$
 * Division:

So,  contains the coefficients of the quotient and   the coefficients of the remainder of y and a.

roots(p) This returns a vector containing all the roots of the polynomial with coefficients in.
 * Root finding:

q = polyder(p) This returns the coefficients of the derivative of the polynomial whose coefficients are given by vector.
 * Derivative:

q = polyint(p) This returns the coefficients of the integral of the polynomial whose coefficients are represented by the vector. The constant of integration is set to 0.
 * Integration:

p = polyfit(x, y, n) This returns the coefficients of a polynomial $$p(x)$$ of degree $$n$$ that best fits the data $$(x_i, y_i)$$ in the least squares sense.
 * Data fitting:

Warning: Adding polynomials
Since polynomials are represented by vectors of their coefficients, adding polynomials is not straightforward in Octave. For example, we define the polynomials $$p(x) = x^2 - 1$$ and $$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 ( and  ) of different lengths. This operation is not defined. To work around this, you have to add some leading zeroes to. 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