(PHP) Matrix Class - Perform Algebraic functions on Matrices

By Sorasyn on Dec 07, 2013

As the title states, this is just a small class I've written to represent a Matrix object as seen every so often in various disciplines of mathematics. Matrices are, in programming terms, basically a two dimensional array of integers that can represent anything from trigonometric angles, and vectors; to any number of notable applications including tracking network paths, and applying cryptography calculations, among other things.

I've included a number of functions as well that not only allow for manipulation of the matrix's data, but to also perform algebraic calculations between numbers and matrices, or between two matrices.

SetElem($x, $y,$val) => Sets the specified coordinates of the target matrix object to the value given in the parameters. The coordinates must be valid for any value to be set.

GetElem($x, $y) => Gets the value stored at the specified coordinates. Again the coordinates must be valid to get a value returned.

Add($matrix) => Adds two matrices together by comparing each set of coordinates from each Matrix object and storing the result in an entirely new Matrix object. Matrix dimensions have to be identical. Returns a Matrix object,

Subtract($matrix) => Subtracts two matrices by comparing each set of coordinates from each Matrix Object and storing the result in an entirely new Matrix object,, Matrix dimensions have to be identical. Returns a Matrix object.

Multiply($matrix) => Multiplies both Matrix objects together by computing the Dot Product from each Matrix, and storing the resulting numbers in a new Matrix object. The number of rows in the original Matrix object must equal the columns of the target Matrix object. (Ex. A 2x3 Matrix can only be multiplied with a 3x2 Matrix.)

ScalarMultiply($num) => Multiplies all elements in the target Matrix object by a given number, hence "scaling."

Note: Please contact me if there's any bugs I didn't catch. I think I got everything written in such a way that all data is accessed through their respective instances like any other proper OOP implementation.

<?php 
class Matrix {
    public $arr, $rows, $cols;

    function Matrix($row, $col) {
        if ($row > 0 && $col > 0) {
            $arr        = array();
            $this->rows = $row;
            $this->cols = $col;

            for ($a=0; $a < $this->rows; $a++) {
                array_push($arr,array());

                for ($b=0; $b < $this->cols; $b++) {
                    array_push($arr[$a],0);
                }
            }
        }
    }

    function SetElem($x, $y, $val) {
        if ($x > -1 && $x < $this->rows) {
            if ($y > -1 && $y < $this->cols) {
                $this->arr[$x][$y] = $val;
            }
        }
    }

    function GetElem($x, $y) {
        if ($x > -1 && $x < $this->rows) {
            if ($y > -1 && $y < $this->cols) {
                return $this->arr[$x][$y];
            }
        }
    }

    function Add($matrix) {
        if ($this->rows == $matrix->rows && $this->cols == $matrix->cols) {
            $rslt = new Matrix($this->rows,$this->cols);

            for ($a=0; $a < $this->rows; $a++) {
                for ($b=0; $b < $this->cols; $b++) {
                    $rslt->SetElem($a,$b,$this->GetElem($a,$b) + $matrix->GetElem($a,$b));
                }
            }

            return $rslt;
        }
    }

    function Subtract($matrix) {
        if ($this->rows == $matrix->rows && $this->cols == $matrix->cols) {
            $rslt = new Matrix($this->rows,$this->cols);

            for ($a=0; $a < $this->rows; $a++) {
                for ($b=0; $b < $this->cols; $b++) {
                    $rslt->SetElem($a,$b,$this->GetElem($a,$b) - $matrix->GetElem($a,$b));
                }
            }

            return $rslt;
        }
    }

    function Multiply($matrix) {
        if ($this->cols == $matrix->rows) {
            $rslt = new Matrix($this->rows, $matrix->cols);

            for ($a=0; $a < $rslt->rows; $a++) {
                for ($b=0; $b < $rslt->cols; $b++) {
                    $total = 0;

                    for ($c=0; $c < $matrix->rows; $c++) {
                        $total += $this->GetElem($a,$c) * $matrix->GetElem($c,$b);
                    }

                    $rslt->SetElem($a,$b,$total);
                }
            }

            return $rslt;
        }
    }

    function ScalarMultiply($num) {
        $rslt = new Matrix($this->rows,$this->cols);

        for  ($a=0; $a < $rslt->rows; $a++) {
            for  ($b=0; $b < $rslt->cols; $b++) {
                $rslt->SetElem($a,$b,$this->GetElem($a,$b) * $num);
            }
        }

        return $rslt;
    }
}
?>

Usage:

<?php include 'Matrix.php'; 
$mat = new Matrix(2,2);

$mat->SetElem(0,0,1);
$mat->SetElem(0,1,2);
$mat->SetElem(1,0,3);
$mat->SetElem(1,1,4);

$mat2 = new Matrix(2,2);

$mat2->SetElem(0,0,5);
$mat2->SetElem(0,1,6);
$mat2->SetElem(1,0,7);
$mat2->SetElem(1,1,8);

$MultiplyResult = $mat->Multiply($mat2);
$ScalarResult   = $mat->ScalarMultiply(2);
$AddResult      = $mat->Add($mat2);
$SubtractResult = $mat->Subtract($mat2);
?>

Comments

Sign in to comment.
Hawkee   -  Dec 07, 2013

Neat, I remember doing this stuff in my 3D programming class.

Sorasyn  -  Dec 07, 2013

Yeah, we covered them in Trigonometry awhile back to transform 2D vectors. I thought it'd be a nice small project to do, and I have been wanting to dig into PHP a little bit.

I'd like to say that OOP in PHP is different than I'm used to with say, C#, but truthfully it's not. It does, however, require $this-> each time you reference any in class variables or functions, which gets old after awhile. It was a treat figuring out how to build a two dimensional array, though.

Hawkee  -  Dec 08, 2013

Looks like some very clean code.

Sorasyn  -  Dec 08, 2013

Thanks! I'm not really fond of having too many nested loops at once, but it's somewhat unavoidable in this instance. I'd like to have added the ability to invert matrices, but that's a sticky business regarding rules and what not for any matrix with dimensions greater than 2x2.

Jonesy44  -  Dec 12, 2013

Inverting matrices is a pain but the one thing a computer can definitely do better than a human. Maybe start by just calculating the determinant. Nice code though - MATLAB is the bomb for doing this kind of stuff :-)

Sign in to comment

Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.