🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI Freenp.linalg.eig: Eigenvalues and Eigenvectors

A square matrix can be analyzed by finding its eigenvalues and eigenvectors. NumPy’s np.linalg.eig returns the eigenvalues and right eigenvectors, with each vector in the column matched to its value by index.
This article shows how to compute eigenpairs with NumPy and select a matching value-vector pair.
TL;DR
Call np.linalg.eig(A) for a square matrix, then use vectors[:, i] with values[i] and check A @ vectors against vectors * values.
- Eigenvalues are not guaranteed to be sorted.
- Columns of the returned eigenvector array hold right eigenvectors.
- For a symmetric or Hermitian matrix, prefer np.linalg.eigh.
What Does np.linalg.eig Return?
An eigenvector is a nonzero direction that a matrix transforms by scaling, and its eigenvalue is that scale. In symbols, A v = lambda v.
The routine accepts a square array A and returns the values and right vectors for the equation. For a diagonalizable matrix with distinct eigenvalues, the vector columns form a basis that can represent the matrix in diagonal form.
The result contains eigenvalues with shape (…, M) and eigenvectors with shape (…, M, M), where the final dimensions describe each M by M matrix. NumPy normalizes each vector to unit length, but its sign or complex phase can vary across valid results.
For one matrix of size M by M, values has M entries and vectors has M rows and M columns. The value at index i belongs to the vector in column i. This is a right eigenvector because the matrix multiplies the vector from the left, as in A v = lambda v.
The word eigenpair refers to that value-vector match. The two returned arrays are separate, so their shared index carries the relationship. Treating a row as the vector or sorting only values breaks that relationship even when both arrays still look plausible.
For a diagonalizable matrix, collect the eigenvectors as columns of V and the eigenvalues along the diagonal of D. Then A V = V D, which gives A = V D V inverse when V is invertible. This view is useful when the task asks for a decomposition, but computing eigenpairs alone does not guarantee that inverse exists.
A repeated eigenvalue can have fewer independent eigenvectors than its algebraic multiplicity. The matrix can then fail to have a complete eigenvector basis, so do not build a diagonalization by assuming every returned eigenvector matrix can be inverted.
Complex output is also valid for an input with non-complex entries. A planar rotation is one example. Its eigen-directions require complex coordinates, so casting NumPy’s result to float can discard meaningful information.
The routine can operate on stacks of matrices too. In a batch shaped (B, M, M), the leading B dimension identifies matrices, while the final two dimensions identify each square matrix. The result shapes are (B, M) and (B, M, M), so select a batch with values[b] and vectors[b] before applying the single-matrix column interpretation.
I use the column index to pair each result because the vector matrix stores one eigenvector per column.
A matrix with non-complex entries can still have complex eigenvalues in conjugate pairs. A rotation matrix, for example, has no non-complex eigenvector directions, so its output requires complex numbers.
Repeated eigenvalues may share fewer independent eigenvectors than their multiplicity suggests. In that case, the returned vector matrix may not have full rank, so an inverse-based diagonalization is not guaranteed.
How to Compute Eigenpairs Step by Step
Use a square NumPy array, unpack the two returned arrays, and check the defining equation with a numerical tolerance.
Step 1: Create a square array
Each input matrix must have the same number of rows and columns. A Python nested list works, though converting it with np.array makes its numeric shape explicit. The example below uses a symmetric matrix so its result can be checked directly.
A matrix is a rectangular grid of numbers. For eig, it must be square because the transformation maps a vector in an M-dimensional space back into that same space. A row count and column count that differ cannot satisfy the required eigenvalue equation for this routine.
When the data comes from another calculation, check its shape before computing eigenpairs. A shape such as (3, 3) represents a valid single matrix, while a shape such as (2, 3) does not. For batched data, each matrix must still have equal final dimensions even if the leading batch dimensions differ.
Step 2: Compute and inspect the returned arrays
Save the following as eig_demo.py and run python3 eig_demo.py. The printed columns are normalized eigenvectors.
import numpy as np
matrix = np.array([[2.0, 1.0], [1.0, 3.0]])
values, vectors = np.linalg.eig(matrix)
print("eigenvalues:", np.round(values, 6))
print("eigenvectors:")
print(np.round(vectors, 6))
print("residual check:", np.allclose(matrix @ vectors, vectors * values))
print("column norms:", np.round(np.linalg.norm(vectors, axis=0), 6))
The command prints this output:
eigenvalues: [1.381966 3.618034]
eigenvectors:
[[-0.850651 -0.525731]
[ 0.525731 -0.850651]]
residual check: True
column norms: [1. 1.]

The check is vectorized: multiplying the matrix by every eigenvector column gives the same result as multiplying each column by its eigenvalue. np.allclose allows small floating-point differences instead of demanding exact equality.
The output has two values and a 2 by 2 vector array. Read down a column for one vector, not across a row. The norm line checks each column’s length, which is one here.
The residual check evaluates the defining equation for all columns at once. A true result says the computed arrays agree within np.allclose’s default tolerance for this example. For a larger or badly scaled problem, choose a tolerance suited to the size and numerical scale of the data rather than interpreting a boolean as an exact proof.
The returned eigenvectors are normalized, so comparing their raw entries with an answer from another solver can be misleading. Multiplying an eigenvector by any nonzero scalar still gives an eigenvector for the same eigenvalue. Compare the equation or the direction, allowing for sign or complex phase changes.
I ran python3 eig_demo.py and got a True residual check with unit norms for both columns.
Step 3: Select a matching eigenpair
To inspect one pair, use values[i] with vectors[:, i]. The expression vectors[i] selects a row instead. This matters when passing the vector to a later matrix calculation.
In NumPy indexing, the colon keeps every row and i chooses one column. The resulting one-dimensional vector can be used in a matrix-vector product. Keep the corresponding scalar in values[i] so a direct check can compare matrix @ vector with value * vector.
A useful mental model is a two-column table: each column position is a label shared by one value and one vector. If you pass the full vector matrix into another routine, check whether that routine expects vectors in columns or rows. A transpose may be needed for a different convention, but do not change NumPy’s returned representation before understanding that interface.
When matrix data is batched, leading dimensions can hold multiple matrices and the final two dimensions still describe each matrix. See the NumPy reference for broadcasting details before reshaping a batch.
For a batch, first select the matrix index and then select the eigenpair column within that matrix. In other words, vectors[b, :, i] is the i-th vector for matrix b, and values[b, i] is its partner. Keeping those two indices aligned avoids mixing eigenpairs from different matrices.
Ordering, Errors, and Choosing eigh
Eigenvalues can be ordered with an index permutation applied to the vector columns in the same way.
For complex values, NumPy orders first by the non-complex component, then by the imaginary component. Choose a task-specific convention when that rule does not express your priority.
Sorting is a presentation or downstream-analysis choice, not part of the mathematical pairing. np.argsort returns indices that would place a one-dimensional array in order. Applying that same index array to the columns preserves which vector belongs to each value.
For non-complex values, a common choice is ascending numeric order. Complex values have no ordinary less-than order, so NumPy orders them first by the non-complex component, then by the imaginary component. To prioritize magnitude instead, define that key with np.abs(values) and apply the resulting indices to both arrays.
I apply one argsort index array to values and columns because the probe showed the returned pair order should not be assumed.
order = np.argsort(values)
values = values[order]
vectors = vectors[:, order]
The first assignment creates a permutation, and the next two assignments use it consistently. For a descending order, reverse the index array or sort a chosen key in descending order. Do not independently sort the vector entries: a vector is a whole column, not a scalar value.
A nonsquare input raises numpy.linalg.LinAlgError with the message “Last 2 dimensions of the array must be square”.
That message points to the input shape, not a failure to converge. Inspect A.shape and correct the data source or reshape only when the existing values genuinely represent a square matrix. Padding a matrix or dropping a column merely to silence the error changes the problem being solved.
The NumPy reference also documents LinAlgError when the computation does not converge. That is distinct from a shape error: a valid square input can still be numerically difficult. Check the data for non-finite values and consider whether the matrix has a special structure that calls for a more suitable routine.
For a covariance matrix, np.linalg.eigh handles symmetric or Hermitian input and its guides explain the eigh routine and the values-only eigvalsh routine.
A covariance matrix should be symmetric in exact arithmetic. Floating-point construction can leave small asymmetries. Use eigh for a symmetric or Hermitian problem.
Do not choose eigh just because the entries look close to symmetric. If the source should be symmetric, verify that expectation first and decide how to handle any discrepancy. Replacing A with (A + A.T) / 2 is a modeling decision that changes the input, not a neutral formatting step.
Use eigvals when a general square matrix’s eigenvalues are needed without eigenvectors. Use eigvalsh for values from symmetric or Hermitian input. Choosing a values-only routine avoids asking the library for results the task does not need.
For a 2 by 2 matrix, its two eigenvalues are the roots of the characteristic equation. Each vector marks a direction preserved up to scaling. A 3 by 3 input uses the same call and returns three values with three vector columns.
When only values are needed for a general matrix, np.linalg.eigvals omits the vector calculation. For eigenvalue decomposition context, see eigenvalue decomposition in Python.
Conclusion
Start with a square input, then check how each returned value relates to its vector. The NumPy reference documents algorithm details and convergence behavior.
For exact output shapes and the nonconvergence exception, consult the NumPy eig reference and the NumPy eigh reference.
Eigenpairs are useful when a transformation’s invariant directions matter, including matrix decomposition and analyses that build on spectral information. The practical workflow is to define the matrix clearly, check that its shape fits the routine, and verify the relationship between each value and column.
Keep the general routine for a general square matrix. When the input is known to be symmetric or Hermitian, select the specialized routine and use its documented guarantees. That choice makes the code express the structure you expect from the data.
FAQ
These answers cover sorting and pairing, two common points of confusion after the first eig call.
Does np.linalg.eig sort eigenvalues?
No. NumPy documents that eigenvalues are not necessarily ordered. Sort with an index array and use those same indices on eigenvector columns.
Which eigenvector belongs to an eigenvalue?
The column vectors[:, i] belongs to values[i]. Verify the pair using A @ vectors[:, i] ≈ values[i] * vectors[:, i].
When should I use np.linalg.eigh?
Use eigh for real symmetric or complex Hermitian matrices. It returns eigenvalues in ascending order and corresponding eigenvectors.


