Matrix Operations

Overview

Matrix operations are central to linear algebra, where matrices represent linear maps, coordinate transforms, and coupled systems of equations. In this category, the core idea is matrix structure: properties like size, rank, singularity, and conditioning determine which computations are valid and numerically reliable. These operations matter in data analysis, optimization, signal processing, and scientific simulation because many workflows reduce to solving Ax=b, measuring matrix magnitude, or composing block transforms. Practical matrix tools help analysts move from abstract algebra to robust computational pipelines.

The unifying concepts are invertibility, operator size, and tensor-style composition. Invertibility separates problems that admit exact inverse-based solutions from those that require generalized least-squares methods. Norms quantify matrix or vector magnitude and are used to reason about stability and sensitivity, including condition behavior under perturbation. Product constructions such as Kronecker-type operators expand low-dimensional structure into larger systems while preserving algebraic patterns.

These functions are implemented with SciPy Linear Algebra (scipy.linalg), the high-level numerical linear algebra layer in SciPy. SciPy provides tested LAPACK/BLAS-backed routines for dense matrix computation, including determinants, inverses, pseudoinverses, norms, and structured products. The library is designed for scientific Python workloads where numerical accuracy, performance, and consistent APIs are all important.

The pair DET and INV covers classical square-matrix diagnostics and exact inversion workflows. DET computes \det(A), which is a compact test for singularity: when \det(A)=0, the matrix is not invertible. INV returns A^{-1} for nonsingular square matrices and is useful for explicit transformation reversal, calibration maps, and algebraic derivations. In practical modeling, these two tools are most informative together: determinant for feasibility checks, inverse for direct map reconstruction when conditioning is acceptable.

PINV extends inversion to rectangular or rank-deficient matrices through the Moore-Penrose pseudoinverse, supporting stable least-squares style workflows when INV is undefined. With SVD-based construction, PINV enables solutions that minimize residual error and can expose effective rank behavior via tolerance settings. MATRIX_NORM complements this by quantifying matrix/vector magnitude under Frobenius, spectral, nuclear, and other orders, which is useful for regularization, convergence checks, and scale comparison across models. Together, PINV, MATRIX_NORM, and DET give a practical toolkit for diagnosing solvability, robustness, and numerical sensitivity.

The structured-product tools KRON and KHATRI_RAO build larger operators from smaller factors with different semantics. KRON forms the full Kronecker product A \otimes B, creating block-structured matrices used in separable PDE discretizations, covariance modeling, and multidimensional basis construction. KHATRI_RAO applies a column-wise Kronecker product, preserving column alignment and appearing in tensor factorization, multilinear regression, and latent-factor estimation pipelines. Used together, these two operations support scalable representations where repeated structure is exploited instead of materializing arbitrary dense operators.

DET

Computes the determinant of a square matrix. The determinant is a scalar value that can be computed from the elements of a square matrix and encodes certain properties of the linear transformation described by the matrix.

Excel Usage

=DET(matrix)
  • matrix (list[list], required): Square 2D array of numeric values.

Returns (float): The determinant of the matrix.

Example 1: Determinant of 2x2 matrix

Inputs:

matrix
1 2
3 4

Excel formula:

=DET({1,2;3,4})

Expected output:

-2

Example 2: Determinant of 3x3 matrix

Inputs:

matrix
1 2 3
4 5 6
7 8 9

Excel formula:

=DET({1,2,3;4,5,6;7,8,9})

Expected output:

0

Python Code

Show Code
import numpy as np
from scipy.linalg import det as scipy_det

def det(matrix):
    """
    Compute the determinant of a square matrix.

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.det.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        matrix (list[list]): Square 2D array of numeric values.

    Returns:
        float: The determinant of the matrix.
    """
    try:
        def to2d(x):
            return [[x]] if not isinstance(x, list) else x

        matrix = to2d(matrix)

        if not isinstance(matrix, list) or not matrix or not all(isinstance(row, list) for row in matrix):
            return "Error: matrix must be a non-empty 2D list"

        n = len(matrix)
        if any(len(row) != n for row in matrix):
            return "Error: matrix must be square (n x n)"

        try:
            a = np.array(matrix, dtype=float)
        except (ValueError, TypeError):
            return "Error: matrix entries must contain numeric values"

        if not np.all(np.isfinite(a)):
            return "Error: matrix must contain only finite numbers"

        try:
            res = scipy_det(a)
        except Exception as e:
            return f"Error: {str(e)}"

        return float(res)

    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator

Square 2D array of numeric values.

INV

Computes the matrix A^{-1} such that AA^{-1} = I, where I is the identity matrix. The input matrix must be square and non-singular. For solving linear systems, using solve is generally more efficient and stable than computing an explicit inverse.

Excel Usage

=INV(matrix)
  • matrix (list[list], required): Square 2D array of numeric values to invert.

Returns (list[list]): 2D array representing the matrix inverse.

Example 1: Inverse of 2x2 matrix

Inputs:

matrix
1 2
3 4

Excel formula:

=INV({1,2;3,4})

Expected output:

Result
-2 1
1.5 -0.5
Example 2: Attempt to invert singular matrix

Inputs:

matrix
1 2
2 4

Excel formula:

=INV({1,2;2,4})

Python Code

Show Code
import numpy as np
from scipy.linalg import inv as scipy_inv

def inv(matrix):
    """
    Compute the inverse of a square matrix.

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.inv.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        matrix (list[list]): Square 2D array of numeric values to invert.

    Returns:
        list[list]: 2D array representing the matrix inverse.
    """
    try:
        def to2d(x):
            return [[x]] if not isinstance(x, list) else x

        matrix = to2d(matrix)

        if not isinstance(matrix, list) or not matrix or not all(isinstance(row, list) for row in matrix):
            return "Error: matrix must be a non-empty 2D list"

        n = len(matrix)
        if any(len(row) != n for row in matrix):
            return "Error: matrix must be square (n x n)"

        try:
            a = np.array(matrix, dtype=float)
        except (ValueError, TypeError):
            return "Error: matrix entries must contain numeric values"

        if not np.all(np.isfinite(a)):
            return "Error: matrix must contain only finite numbers"

        try:
            res = scipy_inv(a)
        except np.linalg.LinAlgError:
            return "Error: Matrix is singular and cannot be inverted"
        except Exception as e:
            return f"Error: {str(e)}"

        return res.tolist()

    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator

Square 2D array of numeric values to invert.

KHATRI_RAO

Computes the Khatri-Rao product (column-wise Kronecker product) of two matrices. If A and B both have N columns, the result is a matrix with N columns where the j-th column is the Kronecker product of the j-th columns of A and B.

Excel Usage

=KHATRI_RAO(matrix_a, matrix_b)
  • matrix_a (list[list], required): First input matrix.
  • matrix_b (list[list], required): Second input matrix.

Returns (list[list]): 2D array representing the Khatri-Rao product.

Example 1: Khatri-Rao product of 2x2 matrices

Inputs:

matrix_a matrix_b
1 2 5 6
3 4 7 8

Excel formula:

=KHATRI_RAO({1,2;3,4}, {5,6;7,8})

Expected output:

Result
5 12
7 16
15 24
21 32

Python Code

Show Code
import numpy as np
from scipy.linalg import khatri_rao as scipy_khatri_rao

def khatri_rao(matrix_a, matrix_b):
    """
    Compute the Khatri-Rao product of two matrices.

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.khatri_rao.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        matrix_a (list[list]): First input matrix.
        matrix_b (list[list]): Second input matrix.

    Returns:
        list[list]: 2D array representing the Khatri-Rao product.
    """
    try:
        def to2d(x):
            return [[x]] if not isinstance(x, list) else x

        a = np.array(to2d(matrix_a), dtype=float)
        b = np.array(to2d(matrix_b), dtype=float)

        if a.shape[1] != b.shape[1]:
            return "Error: Matrices must have the same number of columns"

        try:
            res = scipy_khatri_rao(a, b)
        except Exception as e:
            return f"Error: {str(e)}"

        return res.tolist()

    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator

First input matrix.
Second input matrix.

KRON

Computes the Kronecker product, often denoted by \otimes. If A is an m \times n matrix and B is a p \times q matrix, then the Kronecker product A \otimes B is an mp \times nq block matrix.

Excel Usage

=KRON(matrix_a, matrix_b)
  • matrix_a (list[list], required): First input matrix.
  • matrix_b (list[list], required): Second input matrix.

Returns (list[list]): 2D array representing the Kronecker product.

Example 1: Kronecker product of two 2x2 identity matrices

Inputs:

matrix_a matrix_b
1 0 1 0
0 1 0 1

Excel formula:

=KRON({1,0;0,1}, {1,0;0,1})

Expected output:

Result
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
Example 2: Kronecker product with a scalar

Inputs:

matrix_a matrix_b
2 1 2
3 4

Excel formula:

=KRON({2}, {1,2;3,4})

Expected output:

Result
2 4
6 8

Python Code

Show Code
import numpy as np
from scipy.linalg import kron as scipy_kron

def kron(matrix_a, matrix_b):
    """
    Compute the Kronecker product of two matrices.

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.kron.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        matrix_a (list[list]): First input matrix.
        matrix_b (list[list]): Second input matrix.

    Returns:
        list[list]: 2D array representing the Kronecker product.
    """
    try:
        def to2d(x):
            return [[x]] if not isinstance(x, list) else x

        a = np.array(to2d(matrix_a), dtype=float)
        b = np.array(to2d(matrix_b), dtype=float)

        try:
            res = scipy_kron(a, b)
        except Exception as e:
            return f"Error: {str(e)}"

        return res.tolist()

    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator

First input matrix.
Second input matrix.

MATRIX_NORM

Calculates various matrix or vector norms based on the ‘ord’ parameter. By default, it computes the Frobenius norm for matrices and the L2 norm for vectors.

Excel Usage

=MATRIX_NORM(matrix, ord_type, ord_val)
  • matrix (list[list], required): 2D array of numeric values.
  • ord_type (str, optional, default: “fro”): Type of norm to compute. Choose from common types or provide a numeric value.
  • ord_val (float, optional, default: 2): Numeric order of the norm (if ord_type is set to ‘numeric’).

Returns (float): The calculated norm.

Example 1: Frobenius norm of 2x2 matrix

Inputs:

matrix ord_type
1 2 fro
3 4

Excel formula:

=MATRIX_NORM({1,2;3,4}, "fro")

Expected output:

5.47723

Example 2: L2 norm of a vector (as 1xN matrix)

Inputs:

matrix ord_type
3 4 2

Excel formula:

=MATRIX_NORM({3,4}, 2)
Example 3: Nuclear norm

Inputs:

matrix ord_type
1 0 nuc
0 1

Excel formula:

=MATRIX_NORM({1,0;0,1}, "nuc")

Expected output:

2

Example 4: L3 norm of a vector

Inputs:

matrix ord_type ord_val
1 2 2 numeric 3

Excel formula:

=MATRIX_NORM({1,2,2}, "numeric", 3)

Expected output:

2.57128

Python Code

Show Code
import numpy as np
from scipy.linalg import norm as scipy_norm

def matrix_norm(matrix, ord_type='fro', ord_val=2):
    """
    Compute matrix or vector norm.

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.norm.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        matrix (list[list]): 2D array of numeric values.
        ord_type (str, optional): Type of norm to compute. Choose from common types or provide a numeric value. Valid options: Frobenius (Matrix default), Nuclear, Max absolute (inf), Min absolute (-inf), 1-norm, 2-norm (Spectral), Numeric. Default is 'fro'.
        ord_val (float, optional): Numeric order of the norm (if ord_type is set to 'numeric'). Default is 2.

    Returns:
        float: The calculated norm.
    """
    try:
        def to2d(x):
            return [[x]] if not isinstance(x, list) else x

        matrix = to2d(matrix)

        try:
            a = np.array(matrix, dtype=float)
        except (ValueError, TypeError):
            return "Error: matrix entries must contain numeric values"

        if not np.all(np.isfinite(a)):
            return "Error: matrix must contain only finite numbers"

        # Handle ord
        ot = ord_type.lower()
        if ot == "numeric":
            order = ord_val
        elif ot in ("1", "2"):
            order = int(ot)
        elif ot == "inf":
            order = np.inf
        elif ot == "-inf":
            order = -np.inf
        else:
            order = ot

        # Fix for vectors: if order is numeric (not fro or nuc) and input is 1D, flatten it
        if order not in ("fro", "nuc") and (a.shape[0] == 1 or a.shape[1] == 1):
            a = a.flatten()

        try:
            res = scipy_norm(a, ord=order)
        except Exception as e:
            return f"Error: {str(e)}"

        return float(res)

    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator

2D array of numeric values.
Type of norm to compute. Choose from common types or provide a numeric value.
Numeric order of the norm (if ord_type is set to 'numeric').

PINV

The Moore–Penrose pseudoinverse generalizes the matrix inverse to non-square or singular matrices. It is widely used for computing least-squares solutions and analyzing the effective rank of a matrix.

Given a matrix A with singular value decomposition A = U\Sigma V^H, the pseudoinverse is defined as A^+ = V \Sigma^+ U^H, where \Sigma^+ replaces each nonzero singular value \sigma with 1/\sigma and transposes the diagonal.

Excel Usage

=PINV(matrix, atol, rtol, return_rank, check_finite)
  • matrix (list[list], required): Matrix to pseudo-invert. Scalars are treated as 1x1 matrices.
  • atol (float, optional, default: 0): Absolute threshold for small singular values to be treated as zero.
  • rtol (float, optional, default: null): Relative threshold for small singular values. If None, uses max(M, N) * eps.
  • return_rank (bool, optional, default: false): If True, return the effective rank instead of the pseudoinverse.
  • check_finite (bool, optional, default: true): If True, verify the input contains only finite numbers.

Returns (list[list]): 2D pseudoinverse matrix, or error message string.

Example 1: Pseudoinverse of a 2x2 invertible matrix

Inputs:

matrix
1 2
3 4

Excel formula:

=PINV({1,2;3,4})

Expected output:

Result
-2 1
1.5 -0.5
Example 2: Pseudoinverse of a 3x2 rectangular matrix

Inputs:

matrix
1 2
3 4
5 6

Excel formula:

=PINV({1,2;3,4;5,6})

Expected output:

Result
-1.33333 -0.333333 0.666667
1.08333 0.333333 -0.416667
Example 3: Effective rank of a 2x2 matrix

Inputs:

matrix return_rank
1 2 true
3 4

Excel formula:

=PINV({1,2;3,4}, TRUE)

Expected output:

2

Example 4: Pseudoinverse with custom atol and rtol thresholds

Inputs:

matrix atol rtol
1 2 0.00001 0.00001
3 4

Excel formula:

=PINV({1,2;3,4}, 0.00001, 0.00001)

Expected output:

Result
-2 1
1.5 -0.5

Python Code

Show Code
import numpy as np
from scipy.linalg import pinv as scipy_pinv

def pinv(matrix, atol=0, rtol=None, return_rank=False, check_finite=True):
    """
    Compute the Moore-Penrose pseudoinverse of a matrix using singular value decomposition (SVD).

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.pinv.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        matrix (list[list]): Matrix to pseudo-invert. Scalars are treated as 1x1 matrices.
        atol (float, optional): Absolute threshold for small singular values to be treated as zero. Default is 0.
        rtol (float, optional): Relative threshold for small singular values. If None, uses max(M, N) * eps. Default is None.
        return_rank (bool, optional): If True, return the effective rank instead of the pseudoinverse. Default is False.
        check_finite (bool, optional): If True, verify the input contains only finite numbers. Default is True.

    Returns:
        list[list]: 2D pseudoinverse matrix, or error message string.
    """
    try:
        # Helper function to normalize scalar/single-element input to 2D list
        def to2d(x):
            return [[x]] if not isinstance(x, list) else x

        # Normalize scalar input into a 2D list for consistent handling
        matrix = to2d(matrix)
        if not isinstance(matrix[0], list):
            # Handle case where input was a 1D list
            return "Error: Invalid input: matrix must be a 2D list or scalar numeric value."

        # Convert scalar values that came from Excel single-element arrays
        for i, row in enumerate(matrix):
            for j, val in enumerate(row):
                if isinstance(val, (int, float, bool)):
                    matrix[i][j] = float(val)
                elif isinstance(val, str):
                    try:
                        matrix[i][j] = float(val)
                    except Exception:
                        return "Error: Invalid input: matrix must contain only numeric values."

        # Ensure the matrix is a 2D list with consistent row lengths
        if not matrix or not all(isinstance(row, list) for row in matrix):
            return "Error: Invalid input: matrix must be a 2D list with at least one row."
        if any(len(row) == 0 for row in matrix):
            return "Error: Invalid input: matrix rows must contain at least one value."
        row_length = len(matrix[0])
        if any(len(row) != row_length for row in matrix):
            return "Error: Invalid input: all rows in matrix must have the same length."

        # Validate optional parameters
        try:
            atol_value = float(atol)
        except Exception:
            return "Error: Invalid input: atol must be a numeric value."

        if rtol is not None:
            try:
                rtol_value = float(rtol)
            except Exception:
                return "Error: Invalid input: rtol must be a numeric value or None."
        else:
            rtol_value = None

        if not isinstance(return_rank, bool):
            return "Error: Invalid input: return_rank must be a boolean."
        if not isinstance(check_finite, bool):
            return "Error: Invalid input: check_finite must be a boolean."

        # Convert the matrix elements to floats, ensuring numeric values
        numeric_rows = []
        for row in matrix:
            numeric_row = []
            for value in row:
                try:
                    numeric_row.append(float(value))
                except Exception:
                    return "Error: Invalid input: matrix must contain only numeric values."
            numeric_rows.append(numeric_row)

        arr = np.array(numeric_rows, dtype=float)

        # Compute the pseudoinverse and optionally the rank
        if return_rank:
            _, rank = scipy_pinv(
                arr,
                atol=atol_value,
                rtol=rtol_value,
                return_rank=True,
                check_finite=check_finite,
            )
            if not np.isfinite(rank):
                return "Error: scipy.linalg.pinv error: effective rank is not finite."
            return float(rank)

        result = scipy_pinv(
            arr,
            atol=atol_value,
            rtol=rtol_value,
            return_rank=False,
            check_finite=check_finite,
        )

        # Ensure the result does not contain non-finite values before returning to Excel
        if not np.all(np.isfinite(result)):
            return "Error: scipy.linalg.pinv error: result contains non-finite values."

        return result.tolist()
    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator

Matrix to pseudo-invert. Scalars are treated as 1x1 matrices.
Absolute threshold for small singular values to be treated as zero.
Relative threshold for small singular values. If None, uses max(M, N) * eps.
If True, return the effective rank instead of the pseudoinverse.
If True, verify the input contains only finite numbers.