[Python] How can I vectorize a function that returns eigenvalues and eigenvectors of a matrix...

Discussão em 'Python' iniciado por Stack, Junho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working with a function in Python that constructs a 4×4 matrix based on inputs (x1, y1, x2, y2), and computes its eigenvalues and eigenvectors using np.linalg.eigh.

    Here is a simplified version of my code:

    import numpy as np

    def f(kx, ky):
    return kx + 1j * ky

    def fs(kx, ky):
    return np.conj(f(kx, ky))

    def eig(x1, y1, x2, y2):
    a = 10
    x = x1 + x2
    y = y1 + y2
    H = np.array([
    [a, f(x, y), f(x, y), fs(x, y)],
    [fs(x, y), a, 0, f(x, y)],
    [fs(x, y), 0, -a, f(x, y)],
    [f(x, y), fs(x, y), fs(x, y), -a]
    ])

    Eval, Evec = np.linalg.eigh(H)
    sorted_indices = np.argsort(Eval)
    return Eval[sorted_indices], Evec[:, sorted_indices]



    Now, I have 1-d arrays of input values:

    x1_array, y1_array, x2_array, y2_array # all same shape


    I want to efficiently vectorize this function across those arrays — i.e., compute all eigenvalues/eigenvectors in a batched way without writing an explicit Python loop if possible.

    Continue reading...

Compartilhe esta Página