EXPM

Overview

The EXPM function computes the matrix exponential of a square matrix, a fundamental operation in linear algebra with widespread applications in solving systems of linear differential equations, control theory, and Lie group theory. Unlike element-wise exponentiation, the matrix exponential is defined through a power series expansion.

For an n \times n matrix A, the matrix exponential is defined as:

e^A = \sum_{k=0}^{\infty} \frac{A^k}{k!} = I + A + \frac{A^2}{2!} + \frac{A^3}{3!} + \cdots

where I is the identity matrix and A^0 = I. This series always converges for any square matrix.

This implementation uses scipy.linalg.expm from the SciPy library, which employs the scaling and squaring algorithm with Padé approximation. This method, described by Al-Mohy and Higham (2009) in “A New Scaling and Squaring Algorithm for the Matrix Exponential”, provides a numerically stable and efficient approach by exploiting the identity e^A = (e^{A/2^s})^{2^s} to reduce the matrix norm before applying a rational Padé approximant. For more details, see the SciPy documentation.

The matrix exponential has important properties: e^0 = I, \det(e^A) = e^{\operatorname{tr}(A)}, and the result is always invertible with (e^A)^{-1} = e^{-A}. When matrices A and B commute (AB = BA), then e^{A+B} = e^A e^B. The function accepts complex-valued matrices and returns complex results when appropriate. For additional mathematical background, see the Wikipedia article on matrix exponential.

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

Excel Usage

=EXPM(matrix)
  • matrix (list[list], required): Square matrix of values convertible to complex numbers

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

Examples

Example 1: Demo case 1

Inputs:

matrix
0 0
0 0

Excel formula:

=EXPM({0,0;0,0})

Expected output:

Result
1 0
0 1

Example 2: Demo case 2

Inputs:

matrix
0 1
0 0

Excel formula:

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

Expected output:

Result
1 1
0 1

Example 3: Demo case 3

Inputs:

matrix
0 0 0
0 0 0
0 0 0

Excel formula:

=EXPM({0,0,0;0,0,0;0,0,0})

Expected output:

Result
1 0 0
0 1 0
0 0 1

Example 4: Demo case 4

Inputs:

matrix
1 2
-1 3

Excel formula:

=EXPM({1,2;-1,3})

Expected output:

Result
-2.2253522639267036 12.435352624735945
-6.217676312367975 10.21000036080925

Python Code

import numpy as np
from scipy.linalg import expm as scipy_expm

def expm(matrix):
    """
    Compute the matrix exponential of a square matrix using scipy.linalg.expm

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

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

    Args:
        matrix (list[list]): Square matrix of values convertible to complex numbers

    Returns:
        list[list]: 2D matrix exponential, or error message string.
    """
    # Threshold for treating values as effectively zero
    EPSILON = 1e-12

    def to2d(x):
        """Normalize single-cell input to 2D list."""
        return [[x]] if not isinstance(x, list) else x

    def format_complex_value(value):
        """Format complex number for output."""
        real_part = float(value.real)
        imag_part = float(value.imag)
        if abs(imag_part) <= EPSILON:
            return real_part
        elif abs(real_part) <= EPSILON:
            return f"{imag_part}j"
        else:
            sign = "+" if imag_part >= 0 else "-"
            imag_value = abs(imag_part)
            return f"{real_part}{sign}{imag_value}j"

    # Normalize input - Excel may provide single-cell 2D range as a scalar
    matrix = to2d(matrix)

    # Validate that matrix is a non-empty 2D list of rows with consistent length
    if not isinstance(matrix, list) or not matrix:
        return [["Invalid input: matrix must be a 2D list with at least one row."]]
    if any(not isinstance(row, list) for row in matrix):
        return [["Invalid input: matrix must be a 2D list with at least one row."]]
    size = len(matrix)
    if any(len(row) != size for row in matrix):
        return [["Invalid input: matrix must be square."]]

    # Convert to a numeric numpy array, rejecting values that cannot form complex numbers
    numeric_rows = []
    for row in matrix:
        numeric_row = []
        for value in row:
            try:
                numeric_row.append(complex(value))
            except Exception:
                return [["Invalid input: matrix entries must be numeric values."]]
        numeric_rows.append(numeric_row)

    arr = np.array(numeric_rows, dtype=np.complex128)
    if not np.isfinite(arr.real).all() or not np.isfinite(arr.imag).all():
        return [["Invalid input: matrix entries must be finite numbers."]]

    # Delegate matrix exponential to SciPy and capture runtime errors
    try:
        result = scipy_expm(arr)
    except Exception as exc:
        return [[f"scipy.linalg.expm error: {exc}"]]

    # Convert result matrix into Excel-friendly values without altering precision
    output = []
    for row in result:
        output_row = []
        for value in row:
            real_part = float(value.real)
            imag_part = float(value.imag)
            if not np.isfinite(real_part) or not np.isfinite(imag_part):
                return [["scipy.linalg.expm error: non-finite result encountered."]]
            output_row.append(format_complex_value(value))
        output.append(output_row)

    return output

Online Calculator