Calculate Eigenvalues of a Matrix

Write a Python function that calculates the eigenvalues of a 2x2 matrix. The function should return a list containing the eigenvalues, sort values from highest to lowest.

Example:

Input:

matrix = [[2, 1], [1, 2]]

Output:

[3.0, 1.0]

Reasoning:

The eigenvalues of the matrix are calculated using the characteristic equation of the matrix, which for a 2x2 matrix is λ2trace(A)λ+det(A)=0, where λ are the eigenvalues.

Code:

import numpy as np

def calculate_eigenvalues(matrix):
    m = np.array(matrix)
    
    if m.shape[0] != m.shape[1]:
        return []
    else:
        return np.linalg.eig(m)[0]