Tuesday, June 14, 2011

Solving Equations using Matlab

Equations and Polynomials in MATLAB

Algebra has a long history shaped by Indian, Babylonian, Egyptian, Greek and Persian mathematicians. Brahmagupta made important contributions to arithmetic, algebra and the treatment of zero, while the word algebra comes from the title of Al-Khwarizmi’s work Al-Kitab al-Mukhtasar fi Hisab al-Jabr wal-Muqabala.

Basic rule of equations

An equation remains balanced when the same valid operation is performed on both sides. If LHS = RHS, then:

  • LHS + x = RHS + x
  • LHS − x = RHS − x
  • LHS × x = RHS × x
  • LHS ÷ x = RHS ÷ x, provided x ≠ 0

Representing a polynomial in MATLAB

MATLAB represents a polynomial using a vector of coefficients arranged in descending powers.

p = [1 0 6 20];

This represents x3 + 6x + 20.

Evaluating the polynomial

Use polyval to evaluate the polynomial for a given value of x.

For x = 1

>> polyval(p, 1)

ans =

    27

For x = 2.5

>> polyval(p, 2.5)

ans =

    50.6250

For the complex value x = 1 + i

>> polyval(p, 1 + i)

ans =

    24.0000 + 8.0000i

Finding the roots

Use the roots function to calculate the roots of the polynomial.

>> roots(p)

ans =

    1.0000 + 3.0000i
    1.0000 - 3.0000i
   -2.0000

The roots can also be stored in a vector:

>> r = roots(p);

Reconstructing the polynomial

Use poly to recover the polynomial coefficients from its roots.

>> v = poly(r)

v =

    1.0000    0.0000    6.0000   20.0000

Plotting the polynomial

Create a vector of x-values, evaluate the polynomial and plot the result.

x = 0:0.01:10;
y = polyval(p, x);
plot(x, y);
grid on;
xlabel('x');
ylabel('p(x)');
title('p(x) = x^3 + 6x + 20');

Multiplying polynomials

Use conv to multiply two polynomials. To multiply the original polynomial by x − 2:

>> product = conv(p, [1 -2])

product =

     1    -2     6     8   -40

The resulting polynomial is x4 − 2x3 + 6x2 + 8x − 40.

Dividing polynomials

Use deconv to divide polynomials. Dividing the product by x − 2 returns the original polynomial:

>> deconv(product, [1 -2])

ans =

     1     0     6    20

Learn With Champak: Practise these commands by changing the coefficients, evaluating the polynomial at different values and comparing the resulting graphs.

No comments:

Post a Comment