Skip to main content
`Ctrl`+`K`

# Linear Algebra Functions

NumPy has a submodule `linalg` for functions related to linear algebra, but the base `numpy` module also contains some linear algebra functions. Linear algebra in NumPy’s documentation provides a comprehensive list of functions. Here we only provide few examples.

    import numpy as np

For mathematical definitions see Linear Algebra.

## Vector Products

For inner products use `np.inner`. For outer products use `np.cross`.

    a = np.array([1, 2, 3])
    b = np.array([1, 0, 2])

    print(np.inner(a, b))
    print(np.cross(a, b))

    7
    [ 4  1 -2]

## Matrix Transpose

The `np.transpose` function yields the transpose of a matrix. Alternatively, a NumPy array’s member variable `T` holds the transpose, too. The transpose is a view (not a copy) of the original matrix.

    A = np.array([[1, 2, 3],
                  [4, 5, 6]])

    print(np.transpose(A))
    print(A.T)

    [[1 4]
     [2 5]
     [3 6]]
    [[1 4]
     [2 5]
     [3 6]]

## Matrix Multiplication

NumPy introduces the `@` operator for matrix multiplication. It’s equivalent to calling `np.matmul`.

    A = np.array([[1, 2, 3],
                  [4, 5, 6]])
    B = np.array([[1, 0],
                  [2, 1],
                  [1, 1]])

    print(A @ B)
    print(np.matmul(A, B))

    [[ 8  5]
     [20 11]]
    [[ 8  5]
     [20 11]]

## Determinants and Inverses

Determinants and inverses of square matrices can be computed with `np.linalg.det` and `np.linalg.inv`, respectively.

    A = np.array([[2, 0],
                  [1, 1]])

    print(np.linalg.det(A))
    print(np.linalg.inv(A))

    2.0
    [[ 0.5  0. ]
     [-0.5  1. ]]

## Solving Systems of Linear Equations

The `np.solve` function solves a system of linear equations.

    A = np.array([[2, 0],
                  [1, 1]])
    b = np.array([2, 3])

    print(np.linalg.solve(A, b))

    [1. 2.]