NumDart

Linear algebra

Solve linear systems, invert matrices and use the QR, LU and SVD decompositions.

Like numpy.linalg

Matrices are Array2d values. The functions live in the linalg module and the decompositions are ports of JAMA.

Solving systems

matrixSolve solves A x = b. With a square A it uses LU; with more rows than columns it returns the least squares solution through QR. b is a column matrix, built with Array2d or arrayToColumnMatrix.

Solve a linear systemSolve A x = b, then check the determinant, inverse and rank of A.
import 'package:scidart/numdart.dart';

void main() {
  // 3x + 2y - z = 1, 2x - 2y + 4z = -2, -x + y/2 - z = 0
  var a = Array2d([
    Array([3, 2, -1]),
    Array([2, -2, 4]),
    Array([-1, 0.5, -1]),
  ]);
  var b = Array2d([
    Array([1]),
    Array([-2]),
    Array([0]),
  ]);

  var x = matrixSolve(a, b);
  print('x = ${matrixColumnToArray(x, 0).toList()}');
  print('det(A) = ${matrixDeterminant(a)}');
  print('rank(A) = ${matrixRank(a)}');
  print('A * x = ${matrixColumnToArray(matrixDot(a, x), 0).toList()}');
}
Output
x = [1.0, -1.9999999999999996, -1.9999999999999993]
det(A) = -3.0000000000000004
rank(A) = 3
A * x = [1.0000000000000002, -1.9999999999999982, -4.440892098500626e-16]

Related functions: matrixDot (matrix product), matrixInverse, matrixPseudoInverse, matrixDeterminant, matrixRank, matrixTranspose, matrixIdentity, matrixNormOne and matrixNormTwo.

Decompositions

QR, LU and SVD decompositionsFactor a matrix and rebuild it from the factors.
import 'package:scidart/numdart.dart';

void main() {
  var a = Array2d([
    Array([4, 3]),
    Array([6, 3]),
  ]);

  var qr = QR(a);
  print('Q = ${qr.Q()}');
  print('R = ${qr.R()}');
  print('Q R = ${matrixDot(qr.Q(), qr.R())}');

  var lu = LU(a);
  print('det from LU = ${lu.det()}');

  var svd = SVD(a);
  print('singular values = ${svd.singularValues().toList()}');
  print('condition number = ${svd.cond()}');
}
Output
Q = Array2d([
  Array([-0.5547001962252291, -0.8320502943378438]),
  Array([-0.8320502943378437, 0.554700196225229])
])
R = Array2d([
  Array([-7.211102550927978, -4.160251471689217]),
  Array([0.0, -0.8320502943378432])
])
Q R = Array2d([
  Array([4.0, 2.999999999999999]),
  Array([6.0, 2.9999999999999996])
])
det from LU = -6.0
singular values = [8.335579122000661, 0.7198060161367538]
condition number = 11.580313216522228
  • QR uses Householder reflections, with the same signs as NumPy. isFullRank accepts a tolerance.
  • LU uses partial pivoting and gives the determinant and solve.
  • SVD gives the singular values, the 2-norm, the condition number and the numerical rank. It throws FormatException for non-finite input.

Edit this guide on GitHub