Matrix Functions

Overview

Matrix functions extend familiar scalar operations such as exponentials, logarithms, trigonometric functions, and powers to square matrices. The key idea is to evaluate a scalar function f on a matrix argument A so that f(A) preserves linear-algebraic structure and supports modeling of coupled systems. In scientific computing, matrix functions are central to differential equations, control, signal processing, quantum mechanics, and stability analysis. They allow engineers and analysts to move from elementwise approximations to mathematically consistent operator-level transformations.

Core Concepts: Most matrix functions are defined through power series, spectral decompositions, or related analytic constructions. For example, the matrix exponential uses e^A=\sum_{k=0}^{\infty} \frac{A^k}{k!}, while other functions are derived from equivalent identities such as \cos(A)=\tfrac{1}{2}(e^{iA}+e^{-iA}). Practical computation depends on robust numerical algorithms (for example, scaling-and-squaring, Schur decompositions, and inverse scaling strategies) that balance stability, accuracy, and performance for nontrivial matrices. These tools therefore unify mathematical rigor with production-grade numerical implementation.

Implementation: This category is implemented with SciPy Linear Algebra, especially the scipy.linalg matrix-function routines. SciPy provides well-tested algorithms for dense numerical linear algebra and is widely used in data science, engineering simulation, and applied mathematics. The Boardflare functions expose these capabilities in spreadsheet-friendly form while preserving the core behavior of the upstream methods.

Exponential and Logarithmic Operators: EXPM computes the matrix exponential, which is the canonical map from continuous linear dynamics to finite-time state transitions and appears in systems \dot{x}=Ax. Unlike element-wise exponentiation (which simply raises each entry to the power of e), the matrix exponential preserves the underlying linear operator structure.

Technical Note: Matrix vs. Element-wise Operations

A common source of confusion in linear algebra is the distinction between a matrix function and an element-wise operation.

  • Element-wise Exp: Computes e raised to the power of each individual cell. In Python, this is np.exp(A).
  • Matrix Exponential (EXPM): Computes the sum of the matrix power series \sum A^k/k!. In Python, this is scipy.linalg.expm(A).

For any non-diagonal matrix, these results will be vastly different. The matrix exponential is required for solving systems of differential equations and modeling state transitions.

Python Example: Matrix vs. Element-wise

import numpy as np
from scipy.linalg import expm

# Define a simple 2x2 matrix
A = np.array([[0, 1],
              [0, 0]])

# 1. Element-wise exponentiation: exp(0)=1, exp(1)=e
exp_elementwise = np.exp(A)
# Result: [[1, 2.718], [1, 1]]

# 2. Matrix exponential: e^A = I + A + A^2/2! + ... 
# Since A^2 = 0, e^A = I + A
exp_matrix = expm(A)
# Result: [[1, 1], [0, 1]]

print("Element-wise Exp(A):\n", exp_elementwise)
print("\nMatrix Exponential (EXPM):\n", exp_matrix)

LOGM computes a matrix logarithm, acting as a local inverse of the exponential when branch and conditioning assumptions are satisfied; this is useful for recovering generators from transition operators and for interpolation on matrix manifolds. Together, these functions support workflows in control design, Markov modeling, and time-propagation analysis where forward and inverse operator transforms are both required.

Trigonometric Matrix Operators: COSM and SINM evaluate matrix cosine and matrix sine, extending oscillatory scalar dynamics to coupled multivariate systems. These are useful in second-order linear systems, vibration analysis, wave-style models, and formulations where solutions can be written in terms of trigonometric matrix functions. Because they operate on the matrix as an operator rather than elementwise entries, they preserve structural relationships between state variables that would otherwise be lost with naive cell-by-cell formulas.

Powers and Roots of Matrices: FRAC_MAT_POW computes fractional (or more general real) matrix powers, and SQRTM specializes this idea to principal matrix square roots. These operations are important in covariance manipulation, diffusion and fractional dynamics, preconditioning, and geometric transforms on positive-definite matrices. In practice, they let analysts construct intermediate operators such as A^{1/2} or A^\alpha for normalization, interpolation, and physically meaningful model parameterizations.

COSM

Computes the matrix cosine of the square matrix A using the matrix exponential.

Excel Usage

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

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

Example 1: Matrix cosine of a zero matrix

Inputs:

matrix
0 0
0 0

Excel formula:

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

Expected output:

Result
1 0
0 1

Python Code

Show Code
import numpy as np
from scipy.linalg import cosm as scipy_cosm

def cosm(matrix):
    """
    Compute the matrix cosine.

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

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

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

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

        a = np.array(to2d(matrix), dtype=float)

        if a.shape[0] != a.shape[1]:
            return "Error: Matrix must be square (n x n)"

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

        def format_complex(res):
            if not np.iscomplexobj(res):
                return (res.reshape(1, -1) if res.ndim == 1 else res).tolist()

            out = []
            for row in (res.reshape(1, -1) if res.ndim == 1 else res):
                out_row = []
                for val in row:
                    if val.imag == 0.0:
                        out_row.append(float(val.real))
                    else:
                        out_row.append({
                            "type": "Double",
                            "basicValue": float(val.real),
                            "properties": {
                                "Real": {"type": "Double", "basicValue": float(val.real)},
                                "Imaginary": {"type": "Double", "basicValue": float(val.imag)},
                                "Magnitude": {"type": "Double", "basicValue": float(np.abs(val))},
                                "Phase": {"type": "Double", "basicValue": float(np.angle(val))}
                            }
                        })
                out.append(out_row)
            return out

        return format_complex(res)

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

Online Calculator

Square 2D array of numeric values.

EXPM

The matrix exponential extends the scalar exponential to square matrices and appears in systems of linear differential equations, control theory, and Markov processes.

It is defined by the convergent power series:

e^A = \sum_{k=0}^{\infty} \frac{A^k}{k!}

This function computes e^A for a square input matrix using SciPy’s stable scaling-and-squaring implementation.

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.

Example 1: Matrix exponential of 2x2 zero matrix returns identity

Inputs:

matrix
0 0
0 0

Excel formula:

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

Expected output:

Result
1 0
0 1
Example 2: Matrix exponential of nilpotent 2x2 matrix

Inputs:

matrix
0 1
0 0

Excel formula:

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

Expected output:

Result
1 1
0 1
Example 3: Matrix exponential of 3x3 zero matrix returns identity

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: Matrix exponential of arbitrary 2x2 matrix

Inputs:

matrix
1 2
-1 3

Excel formula:

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

Expected output:

Result
-2.22535 12.4354
-6.21768 10.21

Python Code

Show 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.
    """
    try:
        # 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 "Error: Invalid input: matrix must be a 2D list with at least one row."
        if any(not isinstance(row, list) for row in matrix):
            return "Error: 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 "Error: 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 "Error: 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 "Error: 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"Error: 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 "Error: scipy.linalg.expm error: non-finite result encountered."
                output_row.append(format_complex_value(value))
            output.append(output_row)

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

Online Calculator

Square matrix of values convertible to complex numbers

FRAC_MAT_POW

Computes A^p, the p-th power of a square matrix A, where p can be any real or complex number (though this implementation focuses on real p).

Excel Usage

=FRAC_MAT_POW(matrix, power)
  • matrix (list[list], required): Square 2D array of numeric values.
  • power (float, required): The power to which to raise the matrix.

Returns (list[list]): 2D array representing the matrix raised to the fractional power.

Example 1: Matrix power 0.5 of a 2x2 identity matrix

Inputs:

matrix power
1 0 0.5
0 1

Excel formula:

=FRAC_MAT_POW({1,0;0,1}, 0.5)

Expected output:

Result
1 0
0 1
Example 2: Matrix power 2 of a 2x2 matrix

Inputs:

matrix power
1 2 2
3 4

Excel formula:

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

Expected output:

Result
7 10
15 22

Python Code

Show Code
import numpy as np
from scipy.linalg import fractional_matrix_power as scipy_frac_pow

def frac_mat_pow(matrix, power):
    """
    Compute the fractional power of a square matrix.

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

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

    Args:
        matrix (list[list]): Square 2D array of numeric values.
        power (float): The power to which to raise the matrix.

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

        a = np.array(to2d(matrix), dtype=float)

        if a.shape[0] != a.shape[1]:
            return "Error: Matrix must be square (n x n)"

        try:
            res = scipy_frac_pow(a, float(power))
        except Exception as e:
            return f"Error: {str(e)}"

        def format_complex(res):
            if not np.iscomplexobj(res):
                return (res.reshape(1, -1) if res.ndim == 1 else res).tolist()

            out = []
            for row in (res.reshape(1, -1) if res.ndim == 1 else res):
                out_row = []
                for val in row:
                    if val.imag == 0.0:
                        out_row.append(float(val.real))
                    else:
                        out_row.append({
                            "type": "Double",
                            "basicValue": float(val.real),
                            "properties": {
                                "Real": {"type": "Double", "basicValue": float(val.real)},
                                "Imaginary": {"type": "Double", "basicValue": float(val.imag)},
                                "Magnitude": {"type": "Double", "basicValue": float(np.abs(val))},
                                "Phase": {"type": "Double", "basicValue": float(np.angle(val))}
                            }
                        })
                out.append(out_row)
            return out

        return format_complex(res)

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

Online Calculator

Square 2D array of numeric values.
The power to which to raise the matrix.

LOGM

Computes the matrix logarithm, which is the inverse of the matrix exponential. For a matrix A, it finds a matrix L such that \exp(L) = A.

Excel Usage

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

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

Example 1: Logarithm of a diagonal matrix

Inputs:

matrix
2.718281828459 0
0 7.389056098931

Excel formula:

=LOGM({2.718281828459,0;0,7.389056098931})

Expected output:

Result
1 0
0 2

Python Code

Show Code
import numpy as np
from scipy.linalg import logm as scipy_logm

def logm(matrix):
    """
    Compute matrix logarithm.

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

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

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

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

        a = np.array(to2d(matrix), dtype=float)

        if a.shape[0] != a.shape[1]:
            return "Error: Matrix must be square (n x n)"

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

        def format_complex(res):
            if not np.iscomplexobj(res):
                return (res.reshape(1, -1) if res.ndim == 1 else res).tolist()

            out = []
            for row in (res.reshape(1, -1) if res.ndim == 1 else res):
                out_row = []
                for val in row:
                    if val.imag == 0.0:
                        out_row.append(float(val.real))
                    else:
                        out_row.append({
                            "type": "Double",
                            "basicValue": float(val.real),
                            "properties": {
                                "Real": {"type": "Double", "basicValue": float(val.real)},
                                "Imaginary": {"type": "Double", "basicValue": float(val.imag)},
                                "Magnitude": {"type": "Double", "basicValue": float(np.abs(val))},
                                "Phase": {"type": "Double", "basicValue": float(np.angle(val))}
                            }
                        })
                out.append(out_row)
            return out

        return format_complex(res)

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

Online Calculator

Square 2D array of numeric values.

SINM

Computes the matrix sine of the square matrix A using the matrix exponential.

Excel Usage

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

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

Example 1: Matrix sine of a zero matrix

Inputs:

matrix
0 0
0 0

Excel formula:

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

Expected output:

Result
0 0
0 0

Python Code

Show Code
import numpy as np
from scipy.linalg import sinm as scipy_sinm

def sinm(matrix):
    """
    Compute the matrix sine.

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

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

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

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

        a = np.array(to2d(matrix), dtype=float)

        if a.shape[0] != a.shape[1]:
            return "Error: Matrix must be square (n x n)"

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

        def format_complex(res):
            if not np.iscomplexobj(res):
                return (res.reshape(1, -1) if res.ndim == 1 else res).tolist()

            out = []
            for row in (res.reshape(1, -1) if res.ndim == 1 else res):
                out_row = []
                for val in row:
                    if val.imag == 0.0:
                        out_row.append(float(val.real))
                    else:
                        out_row.append({
                            "type": "Double",
                            "basicValue": float(val.real),
                            "properties": {
                                "Real": {"type": "Double", "basicValue": float(val.real)},
                                "Imaginary": {"type": "Double", "basicValue": float(val.imag)},
                                "Magnitude": {"type": "Double", "basicValue": float(np.abs(val))},
                                "Phase": {"type": "Double", "basicValue": float(np.angle(val))}
                            }
                        })
                out.append(out_row)
            return out

        return format_complex(res)

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

Online Calculator

Square 2D array of numeric values.

SQRTM

Computes the matrix square root X such that X^2 = A.

Excel Usage

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

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

Example 1: Square root of a 2x2 identity matrix

Inputs:

matrix
1 0
0 1

Excel formula:

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

Expected output:

Result
1 0
0 1
Example 2: Square root of a 2x2 matrix

Inputs:

matrix
4 0
0 9

Excel formula:

=SQRTM({4,0;0,9})

Expected output:

Result
2 0
0 3

Python Code

Show Code
import numpy as np
from scipy.linalg import sqrtm as scipy_sqrtm

def sqrtm(matrix):
    """
    Compute the matrix square root.

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

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

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

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

        a = np.array(to2d(matrix), dtype=float)

        if a.shape[0] != a.shape[1]:
            return "Error: Matrix must be square (n x n)"

        try:
            res, errest = scipy_sqrtm(a, disp=False)
        except Exception as e:
            return f"Error: {str(e)}"

        def format_complex(res):
            if not np.iscomplexobj(res):
                return (res.reshape(1, -1) if res.ndim == 1 else res).tolist()

            out = []
            for row in (res.reshape(1, -1) if res.ndim == 1 else res):
                out_row = []
                for val in row:
                    if val.imag == 0.0:
                        out_row.append(float(val.real))
                    else:
                        out_row.append({
                            "type": "Double",
                            "basicValue": float(val.real),
                            "properties": {
                                "Real": {"type": "Double", "basicValue": float(val.real)},
                                "Imaginary": {"type": "Double", "basicValue": float(val.imag)},
                                "Magnitude": {"type": "Double", "basicValue": float(np.abs(val))},
                                "Phase": {"type": "Double", "basicValue": float(np.angle(val))}
                            }
                        })
                out.append(out_row)
            return out

        return format_complex(res)

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

Online Calculator

Square 2D array of numeric values.