Source for file MagicSquareExample.php
Documentation is available at MagicSquareExample.php
require_once "../Matrix.php";
* Example of use of Matrix Class, featuring magic squares.
* Generate magic square test matrix.
* @param int n dimension of matrix
for ($j = 0; $j < $n; ++ $j)
for ($i = 0; $i < $n; ++ $i)
$M[$i][$j] = $n* (($i+ $j+ $a) % $n) + (($i+ 2* $j+ $b) % $n) + 1;
} else if (($n % 4) == 0) {
for ($j = 0; $j < $n; ++ $j) {
for ($i = 0; $i < $n; ++ $i) {
if ((($i+ 1)/ 2)% 2 == (($j+ 1)/ 2)% 2)
$M[$i][$j] = $n* $n- $n* $i- $j;
for ($j = 0; $j < $p; ++ $j) {
for ($i = 0; $i < $p; ++ $i) {
$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) {
$M[$i][$j] = $M[$i+ $p][$j];
for ($j = $n- $k+ 1; $j < $n; ++ $j) {
$M[$i][$j] = $M[$i+ $p][$j];
$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;
* Simple function to replicate PHP 5 behaviour
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).
<p>Test of Matrix Class, using magic squares.</p>
<p>See MagicSquareExample.main() for an explanation.</p>
<table border='1' cellspacing='0' cellpadding='4'>
for ($n = 3; $n <= 6; ++ $n) {
echo "<td align='right'>$n</td>";
echo "<td align='right'>$t</td>";
$O = $M->plus($M->transpose());
$d = $E->getRealEigenvalues();
echo "<td align='right'>". $d[$n- 1]. "</td>";
echo "<td align='right'>". $r. "</td>";
echo "<td align='right'>". sprintf("%.3f",$c). "</td>";
echo "<td align='right'>Inf</td>";
$LU = new LUDecomposition($M);
// Java version: R = L.times(U).minus(M.getMatrix(p,0,n-1));
$R = $S->minus($M->getMatrix($p,0,$n- 1));
$res = $R->norm1()/ ($n* $eps);
echo "<td align='right'>". sprintf("%.3f",$res). "</td>";
$QR = new QRDecomposition($M);
$res = $R->norm1()/ ($n* $eps);
echo "<td align='right'>". sprintf("%.3f",$res). "</td>";
$etime = $stop_time - $start_time;
echo "<p>Elapsed time is ". sprintf("%.4f",$etime) . " seconds.</p>";
|