矩阵运算就是对两个数据表进行某种数学运算,并得到另一个数据表.
下面的例子中我们创建了一个基本完整的矩阵运算函数库,以便用于矩阵操作的程序中.
// 来自 PHP5 in Practice (U.S.)Elliott III & Jonathan D.Eisenhamer
'; // For each row in the matrix: for ($r = 0; $r < $rows; $r++) { // Begin the row: echo '
'; // For each column in this row for ($c = 0; $c < $columns; $c++) { // Echo the element: echo "{$matrix[$r][$c]} | "; } // End the row. echo '
'; } // End the table. echo "/n"; } else { // It wasn't well formed: return false; } } // Let's do some testing. First prepare some formatting: echo "
/n"; // Now let's test element operations. We need identical sized matrices: $m1 = array( array(5, 3, 2), array(3, 0, 4), array(1, 5, 2), ); $m2 = 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 10 matrix_print(matrix_element_operation($m1, $m2, '+')); // Element subtraction should give us: 1 -6 -3 // -4 -5 4 // -1 3 -6 matrix_print(matrix_element_operation($m1, $m2, '-')); // Do a scalar multiplication on the 2nd matrix: 8 18 10 // 14 10 0 // 4 4 16 matrix_print(matrix_scalar_operation($m2, 2, '*')); // Define some matrices for full matrix operations. // Need to be complements of each other: $m3 = array( array(1, 3, 5), array(-2, 5, 1), ); $m4 = array( array(1, 2), array(-2, 8), array(1, 1), ); // Matrix multiplication gives: 0 31 // -11 37 matrix_print(matrix_operation($m3, $m4, '*')); // Matrix addition gives: 9 20 // 4 15 matrix_print(matrix_operation($m3, $m4, '+')); ?>