MathPHP\LinearAlgebra\MatrixFactory::identity PHP Метод

identity() публичный статический Метод

Example: n = 3; x = 1 [1 0 0] A = [0 1 0] [0 0 1]
public static identity ( integer $n, number $x = 1 ) : SquareMatrix
$n integer size of matrix
$x number (optional; default 1)
Результат SquareMatrix
    public static function identity(int $n, $x = 1) : SquareMatrix
    {
        if ($n < 0) {
            throw new Exception\OutOfBoundsException("n must be ≥ 0. n = {$n}");
        }
        $R = [];
        for ($i = 0; $i < $n; $i++) {
            for ($j = 0; $j < $n; $j++) {
                $R[$i][$j] = $i == $j ? $x : 0;
            }
        }
        return self::create($R);
    }

Usage Example

Пример #1
0
 /**
  * Pivotize creates the permutation matrix P for the LU decomposition.
  * The permutation matrix is an identity matrix with rows possibly interchanged.
  *
  * The product PA results in a new matrix whose rows consist of the rows of A
  * but no rearranged in the order specified by the permutation matrix P.
  *
  * Example:
  *
  *     [α₁₁ α₁₂ α₁₃]
  * A = [α₂₁ α₂₂ α₂₃]
  *     [α₃₁ α₃₂ α₃₃]
  *
  *     [0 1 0]
  * P = [1 0 0]
  *     [0 0 1]
  *
  *      [α₂₁ α₂₂ α₂₃] \ rows
  * PA = [α₁₁ α₁₂ α₁₃] / interchanged
  *      [α₃₁ α₃₂ α₃₃]
  *
  * @return Matrix
  */
 protected function pivotize() : Matrix
 {
     $n = $this->n;
     $P = MatrixFactory::identity($n);
     $A = $this->A;
     // Set initial column max to diagonal element Aᵢᵢ
     for ($i = 0; $i < $n; $i++) {
         $max = $A[$i][$i];
         $row = $i;
         // Check for column element below Aᵢᵢ that is bigger
         for ($j = $i; $j < $n; $j++) {
             if ($A[$j][$i] > $max) {
                 $max = $A[$j][$i];
                 $row = $j;
             }
         }
         // Swap rows if a larger column element below Aᵢᵢ was found
         if ($i != $row) {
             $P = $P->rowInterchange($i, $row);
         }
     }
     return $P;
 }