Exemplo n.º 1
0
 /**
  *    transpose
  *
  *    Tranpose matrix
  * @return Matrix Transposed matrix
  */
 public function transpose()
 {
     $R = new Matrix($this->n, $this->m);
     for ($i = 0; $i < $this->m; ++$i) {
         for ($j = 0; $j < $this->n; ++$j) {
             $R->set($j, $i, $this->matrix[$i][$j]);
         }
     }
     return $R;
 }
 /**
  *    Least squares solution of A*X = B
  *
  * @param Matrix $B A Matrix with as many rows as A and any number of columns.
  * @throws MatrixException
  * @return Matrix Matrix that minimizes the two norm of Q*R*X-B.
  */
 public function solve($B)
 {
     if ($B->getRowDimension() == $this->m) {
         if ($this->isFullRank()) {
             // Copy right hand side
             $nx = $B->getColumnDimension();
             $X = $B->getArray();
             // Compute Y = transpose(Q)*B
             for ($k = 0; $k < $this->n; ++$k) {
                 for ($j = 0; $j < $nx; ++$j) {
                     $s = 0.0;
                     for ($i = $k; $i < $this->m; ++$i) {
                         $s += $this->QR[$i][$k] * $X[$i][$j];
                     }
                     $s = -$s / $this->QR[$k][$k];
                     for ($i = $k; $i < $this->m; ++$i) {
                         $X[$i][$j] += $s * $this->QR[$i][$k];
                     }
                 }
             }
             // Solve R*X = Y;
             for ($k = $this->n - 1; $k >= 0; --$k) {
                 for ($j = 0; $j < $nx; ++$j) {
                     $X[$k][$j] /= $this->rD[$k];
                 }
                 for ($i = 0; $i < $k; ++$i) {
                     for ($j = 0; $j < $nx; ++$j) {
                         $X[$i][$j] -= $X[$k][$j] * $this->QR[$i][$k];
                     }
                 }
             }
             $X = new Matrix($X);
             return $X->getMatrix(0, $this->n - 1, 0, $nx);
         } else {
             throw new MatrixException(5);
         }
     } else {
         throw new MatrixException(3);
     }
 }