[Example] Solving math linear equations with 4 unknown variables

We’ll put some use of Matrix library for CodeIgniter that we already implemented to solve a linear equation.
Let’s say we have linear equations with 4 unknown variables like this:
$latex \begin{array}{rcl}
2a+3b+c+6d &=& 4 \\
4a-2b+0.5c+d &=&2 \\
6a+b-d&=&-1 \\
2a+2b-c+3d&=&4 \end{array}$

That linear equation can be written in Matrix notation like this:
$latex \left[ \begin{matrix} 2&3&1&6\\ 4&-2&0.5&1 \\ 6&1&0&-1\\ 2&2&-1&3 \end{matrix} \right] \left[ \begin{matrix} a\\b\\c\\d \end{matrix} \right] = \left[ \begin{matrix} 4\\2\\-1\\4 \end{matrix} \right] $

And can be solved by this matrix equation:
$latex \left[ \begin{matrix} a\\b\\c\\d \end{matrix} \right] = \left[ \begin{matrix} 2&3&1&6\\ 4&-2&0.5&1 \\ 6&1&0&-1\\ 2&2&-1&3 \end{matrix} \right]^{-1} \left[ \begin{matrix} 4\\2\\-1\\4 \end{matrix} \right] $

And this is how we solve it on php/CodeIgniter:

// load the phpmath library
require_once(APPPATH."/third_party/phpmath/Matrix.php");

//building the 'left' matrix
$left=array(
    array(2,3,1,6),
    array(4, -2, 0.5, 1),
    array(6,1,0,-1),
    array(2,2,-1,3),
);
// left matrix class
$mLeft=new Matrix($left);

//building the 'right' matrix
$right=array(
    array(4),
    array(2),
    array(-1),
    array(4),
);
// right matrix class
$mRight=new Matrix($right);

// calculate inverse of left matrix
$inv_mLeft=$mLeft->inverse();

// find the equation solution by multiplying the inverse of left matrix and the right matrix
$solution=$inv_mLeft->times($mRight);

// $solution is the value of a,b,c and d variables. Let's dump it as an array!
var_dump($solution->getArray());

Quite simple isn’t it?!

PS.: I’m glad I can use my Latex knowledge in this post 😛

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>