The method of using array to realize matrix mathematical operation in PHP

Source: Internet
Author: User
Tags scalar
This article mainly introduces the use of arrays to implement the matrix mathematical operations, combined with specific examples of PHP based on array implementation of matrix representation and operation of the relevant operation skills, the need for friends can refer to the following

Specific as follows:

A matrix operation is a mathematical operation on two data tables, and another data table is obtained.
In the following example, we have created a basic library of matrix operations to be used in the program for matrix operations.

From PHP5 in Practice (U.S.) Elliott III & Jonathan D.eisenhamer

<?php//a Library of matrix Math functions.//all assume a matrix defined by A 2 dimensional array, where the first//i Ndex (Array[x]) is the rows and the second index (array[x][y])//Is the columns//first create a few helper functions// A function to determine if a matrix are well formed. That's to say that//it's perfectly rectangular with no missing values:function _matrix_well_formed ($matrix) {//If th  Is isn't an array, it is badly formed, return false. if (! (  Is_array ($matrix))) {return false;    } else {//Count the number of rows.    $rows = count ($matrix);  Now loops through each row:for ($r = 0; $r < $rows; $r + +) {//Make sure the this-row is set, and an array.      Checking to//See if it is set are ensuring that is a 0 based//numerically indexed array. if (! (      Isset ($matrix [$r]) && is_array ($matrix [$r])) {return false; } else {//If This was row 0, calculate the columns in it:if ($r = = 0) {          $cols = count ($matrix [$r]); Ensure the number of columns is identical else exit} elseif (count ($matrix [$r])! = $cols) {retur        n false; }//Now, loop through all the columns for this row for ($c = 0; $c < $cols; $c + +) {//ensure t He entry is set, and a number if (!) (          Isset ($matrix [$r] [$c]) && is_numeric ($matrix [$r] [$c])) {return false; }}}}}//Ok, if we actually made it this far and then we had not found//anything wrong with the Matr IX. return true; A function to return the ' rows in a ' matrix-//Does not check for validity, it assumes the matrix was well Formed.functi On _matrix_rows ($matrix) {return count ($matrix);} A function to return the columns in a matrix-//Does not check for validity, it assumes the matrix was well Formed.fun Ction _matrix_columns ($matrix) {return count ($matrix [0]);} This function performs operations on MAtrix elements, such as addition//or subtraction. To use it, pass it 2 matrices, and the Operation you//wish to perform, as a string: ' + ', '-' function Matrix_element_opera  tion ($a, $b, $operation) {//Verify both matrices is well formed $valid = false; if (_matrix_well_formed ($a) && _matrix_well_formed ($b)) {//Make sure they has the same number of columns &am P    Rows $rows = _matrix_rows ($a);    $columns = _matrix_columns ($a); if ($rows = = _matrix_rows ($b)) && ($columns = = _matrix_columns ($b))) {//We have a valid setup for C    Ontinuing with element Math $valid = true; }}//If invalid, return False if (! (  $valid)) {return false;} For per element in the matrices perform the operatoin on the//corresponding element in the other array to it:for ($r = 0; $r < $rows; $r + +) {for ($c = 0; $c < $columns; $c + +) {eval (' $a [$r] [$c] '. $operation. '    = $b [$r] [$c]; '); }}//Return the finished Matrix:return $a;} //This function performs full matrix operations, such as matrix addition//or matrix multiplication.  As above, pass it to matrices and the//operation: ' * ', '-', ' + ' function matrix_operation ($a, $b, $operation) {//Verify  Both matrices is well formed $valid = false; if (_matrix_well_formed ($a) && _matrix_well_formed ($b)) {//Make sure they has complementary numbers of rows    and columns.    The number of rows in A should is the number of columns in B $rows = _matrix_rows ($a);    $columns = _matrix_columns ($a); if ($columns = = _matrix_rows ($b)) && ($rows = = _matrix_columns ($b))) {//We have a valid setup for C    Ontinuing $valid = true; }}//If invalid, return False if (! (  $valid)) {return false;}  Create a blank matrix the appropriate size, initialized to 0 $new = Array_fill (0, $rows, array_fill (0, $rows, 0)); For per row in a ... for ($r = 0; $r < $rows; $r + +) {//For each column in B ... for ($c = 0; $c < $rows; $c + +) {/take per member of column B, with each member of row A//and add the results, storing the The N EW table://Loop over each column in A ... for ($ac = 0; $ac < $columns; $ac + +) {//Evaluate the Ope          Ration eval (' $new [$r] [$c] + = $a [$r] [$ac] '.      $operation. ' $b [$AC] [$c]; '); }}}//Return the finished Matrix:return $new;} A function to perform scalar operations. This means the scalar value,//and the operation provided, and apply it to every element.function Matrix_sca  Lar_operation ($matrix, $scalar, $operation) {//Verify it is well formed if (_matrix_well_formed ($matrix)) {$rows =    _matrix_rows ($matrix);    $columns = _matrix_columns ($matrix);  For each element in the matrix, multiply by the scalar for ($r = 0; $r < $rows; $r + +) {for ($c = 0; $c < $columns; $c + +) {eval (' $matrix [$r] [$c] '. $operation. '      = $scalar; '); }}//Return the finished matrix: Return $matrix;  } else {//It wasn ' t well formed:return false; }}//A handy function for printing matrices (as an HTML table) function Matrix_print ($matrix) {//Verify it's well forme    D if (_matrix_well_formed ($matrix)) {$rows = _matrix_rows ($matrix);    $columns = _matrix_columns ($matrix);    Start the table echo ' <table> ';      For each row in the matrix:for ($r = 0; $r < $rows; $r + +) {//Begin the Row:echo ' <tr> '; For per column in this row for ($c = 0; $c < $columns; $c + +) {//Echo the Element:echo "<t      d>{$matrix [$r] [$c]}</td>];      }//End the row.    Echo ' </tr> ';    }//End of the table.  echo "</table>/n";  } else {//It wasn ' t well formed:return false; }}//Let's do some testing. First prepare some Formatting:echo "<mce:style><!--table {border:1px solid black; margin:20px; }TD {text-align:center;} --></mce:style><stylE mce_bogus= "1" >table {border:1px solid black; margin:20px;} td {Text-align:center;} </style>/n ";//Now let ' s test element operations.  We need identical sized matrices: $m 1 = Array (Array (5, 3, 2), array (3, 0, 4), Array (1, 5, 2),), $m 2 = Array (Array (4,                  9, 5), Array (7, 5, 0), Array (2, 2, 8),);//Element addition should give Us:9 12 7//10 5 4//   3 7 10matrix_print (Matrix_element_operation ($m 1, $m 2, ' + '));//element subtraction should give us:1 -6-3// -4-5 4//-1 3-6matrix_print (Matrix_element_operation ($m 1, $m 2, '-                         ')//do a scalar multiplication on the 2nd matrix:8 18 10//14 10 0//  4 4 16matrix_print (Matrix_scalar_operation ($m 2, 2, ' * '))//Define some matrices for full matrix operations.//need to be Complements of each other: $m 3 = Array (Array (1, 3, 5), Array ( -2, 5, 1), $m 4 = Array (Array (1, 2), Array (-2, 8),  Array (1, 1),);//Matrix multiplication gives:0 31// -11 37matrix_print (Matrix_operation ($m 3, $m 4, ' * ')///Matrix addition Gives:9 20//4 15matrix_print (Matrix_operation ($m 3, $m 4, ' + '));? >

Related recommendations:

An example of how PHP implements a clockwise print matrix (Spiral matrix )

adjacency matrix Representation and traversal algorithm of PHP implementation graphs

The method and case of implementing matrix transpose operation of two-dimensional array in PHP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.