magic($p); $M = array(); for ($j = 0; $j < $p; ++$j) { for ($i = 0; $i < $p; ++$i) { $aij = $A->get($i,$j); $M[$i][$j] = $aij; $M[$i][$j+$p] = $aij + 2*$p*$p; $M[$i+$p][$j] = $aij + 3*$p*$p; $M[$i+$p][$j+$p] = $aij + $p*$p; } } for ($i = 0; $i < $p; ++$i) { for ($j = 0; $j < $k; ++$j) { $t = $M[$i][$j]; $M[$i][$j] = $M[$i+$p][$j]; $M[$i+$p][$j] = $t; } for ($j = $n-$k+1; $j < $n; ++$j) { $t = $M[$i][$j]; $M[$i][$j] = $M[$i+$p][$j]; $M[$i+$p][$j] = $t; } } $t = $M[$k][0]; $M[$k][0] = $M[$k+$p][0]; $M[$k+$p][0] = $t; $t = $M[$k][$k]; $M[$k][$k] = $M[$k+$p][$k]; $M[$k+$p][$k] = $t; } return new Matrix($M); } /** * Simple function to replicate PHP 5 behaviour */ function microtime_float() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } /** * Tests LU, QR, SVD and symmetric Eig decompositions. * * n = order of magic square. * trace = diagonal sum, should be the magic sum, (n^3 + n)/2. * max_eig = maximum eigenvalue of (A + A')/2, should equal trace. * rank = linear algebraic rank, should equal n if n is odd, * be less than n if n is even. * cond = L_2 condition number, ratio of singular values. * lu_res = test of LU factorization, norm1(L*U-A(p,:))/(n*eps). * qr_res = test of QR factorization, norm1(Q*R-A)/(n*eps). */ function main() { ?>
Test of Matrix Class, using magic squares.
See MagicSquareExample.main() for an explanation.
n | trace | max_eig | rank | cond | lu_res | qr_res | |
---|---|---|---|---|---|---|---|
$n | "; $M = $this->magic($n); $t = (int) $M->trace(); echo "$t | "; $O = $M->plus($M->transpose()); $E = new EigenvalueDecomposition($O->times(0.5)); $d = $E->getRealEigenvalues(); echo "".$d[$n-1]." | "; $r = $M->rank(); echo "".$r." | "; $c = $M->cond(); if ($c < 1/$eps) echo "".sprintf("%.3f",$c)." | "; else echo "Inf | "; $LU = new LUDecomposition($M); $L = $LU->getL(); $U = $LU->getU(); $p = $LU->getPivot(); // Java version: R = L.times(U).minus(M.getMatrix(p,0,n-1)); $S = $L->times($U); $R = $S->minus($M->getMatrix($p,0,$n-1)); $res = $R->norm1()/($n*$eps); echo "".sprintf("%.3f",$res)." | "; $QR = new QRDecomposition($M); $Q = $QR->getQ(); $R = $QR->getR(); $S = $Q->times($R); $R = $S->minus($M); $res = $R->norm1()/($n*$eps); echo "".sprintf("%.3f",$res)." | "; echo "