Matrix operation library for CodeIgniter

This tips is useful if you someday handling web-based project that involving Matrix handling and you want to implement it using CodeIgniter. We’ll use PHPMath library for this.

  • Download the latest version of phpmath library from here: http://www.phpmath.com/build02/downloads/
  • Open the archive (build02.tar.gz) and see the content, you’ll see “build02” folder, go inside, you’ll see more folders there:
phpmath archive content

phpmath archive content

  • Because we only need the matrix handling and operation library, we just need the “JAMA” folder inside.
  • Extract this “JAMA” folder into your CodeIgniter’s application/third_party/ library, rename it to more meaningful folder, I prefer “phpmath”. Your third_party library will be look like this:
phpmath inside third_party folder

phpmath inside third_party folder

  • Go inside “phpmath” folder, you’ll see more folders there. We don’t need “docs”, “examples” and “tests” folder, we can delete them, your phpmath folder will be like this:
phpmath after deleting unnecessary folders

phpmath after deleting unnecessary folders

And you are done! (In this tips: not like mPDF and PHPExcel library, we don’t need to create a new file/class in the application/libraries folder)

How to use it?

Quite simple, check and test these code samples inside your controller:

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

// define new matrix
$raw_matrix_a=array(
     array(1,2,3,4),
     array(5,6,7,8)
);
$raw_matrix_b=array(
     array(1,2),
     array(3,4),
     array(5,6),
     array(7,8)
);
$raw_matrix_c=array(
     array(9, 10),
     array(11, 12)
);
$raw_matrix_d=array(
     array(13, 14),
     array(15, 16)
);
// build the Matrix class
$mA=new Matrix($raw_matrix_a);
$mB=new Matrix($raw_matrix_b);
$mC=new Matrix($raw_matrix_c);
$mD=new Matrix($raw_matrix_d);

//get the matrix element
var_dump($mA->get(1,1));
//set value
$mA->set(1,1, 0);
//get matrix dimension
var_dump($mA->getRowDimension());
var_dump($mA->getColumnDimension());

//addition
$mE=$mD->plus($mC); //must have same dimension
//subtraction
$mE=$mD->minus($mC);
//multiplication
$mE=$mA->times($mB);
//inverse
$mE=$mD->inverse(); // must be square matrix
//transpose
$mE=$mB->transpose();

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>

Trackbacks and Pingbacks: