solve method

Array2d solve(
  1. Array2d B
)

Least squares solution of AX = B B A Matrix with as many rows as A and any number of columns. return X that minimizes the two norm of QR*X-B.

Implementation

Array2d solve(Array2d B) {
  if (B.row != _m) {
    throw FormatException('Matrix row dimensions must agree.');
  }
  if (!isFullRank()) {
    throw FormatException('Matrix is rank deficient.');
  }

  // Copy right hand side
  var nx = B.column;
  var X = B.copy();

  // Compute Y = transpose(Q)*B
  for (var k = 0; k < _n; k++) {
    for (var j = 0; j < nx; j++) {
      var s = 0.0;
      for (var i = k; i < _m; i++) {
        s += _QR[i][k] * X[i][j];
      }
      s = -s / _QR[k][k];
      for (var i = k; i < _m; i++) {
        X[i][j] += s * _QR[i][k];
      }
    }
  }
  // Solve R*X = Y;
  for (var k = _n - 1; k >= 0; k--) {
    for (var j = 0; j < nx; j++) {
      X[k][j] /= _Rdiag[k];
    }
    for (var i = 0; i < k; i++) {
      for (var j = 0; j < nx; j++) {
        X[i][j] -= X[k][j] * _QR[i][k];
      }
    }
  }
  return (matrixSub(X, 0, _n - 1, 0, nx - 1));
}