Back to Problems

Matrix Transformation (medium)

Write a Python function that transforms a given matrix A using the operation $T^{-1}AS$, where T and S are invertible matrices. The function should first validate if the matrices T and S are invertible, and then perform the transformation. In cases where there is no solution return -1

Example

Example:
        input: A = [[1, 2], [3, 4]], T = [[2, 0], [0, 2]], S = [[1, 1], [0, 1]]
        output: [[0.5,1.5],[1.5,3.5]]
        reasoning: The matrices T and S are used to transform matrix A by computing $T^{-1}AS$.

Matrix Transformation using \(T^{-1}AS\)

Transforming a matrix \(A\) using the operation \(T^{-1}AS\) involves several steps. This operation changes the basis of matrix \(A\) using two invertible matrices \(T\) and \(S\). Given matrices \(A\), \(T\), and \(S\):

1. Check if \(T\) and \(S\) are invertible by ensuring their determinants are non-zero; else return -1.

2. Compute the inverses of \(T\) and \(S\), denoted as \(T^{-1}\) and \(S^{-1}\).

3. Perform the matrix multiplication to obtain the transformed matrix:

\[ A' = T^{-1}AS \]

Example

If: \[ A = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix} \] \[ T = \begin{pmatrix} 2 & 0 \\ 0 & 2 \end{pmatrix} \] \[ S = \begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix} \] First, check that \(T\) and \(S\) are invertible:

• \(\det(T) = 4 \neq 0 \)

• \(\det(S) = 1 \neq 0 \)

Compute the inverses: \[ T^{-1} = \begin{pmatrix} \frac{1}{2} & 0 \\ 0 & \frac{1}{2} \end{pmatrix} \] Then, perform the transformation: \[ A' = T^{-1}AS = \begin{pmatrix} \frac{1}{2} & 0 \\ 0 & \frac{1}{2} \end{pmatrix} \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix} \begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix} = \begin{pmatrix} 0.5 & 1.5 \\ 1.5 & 3.5 \end{pmatrix} \]
import numpy as np

def transform_matrix(A: list[list[int|float]], T: list[list[int|float]], S: list[list[int|float]]) -> list[list[int|float]]:
    # Convert to numpy arrays for easier manipulation
    A = np.array(A, dtype=float)
    T = np.array(T, dtype=float)
    S = np.array(S, dtype=float)
    
    # Check if the matrices T and S are invertible
    if np.linalg.det(T) == 0 or np.linalg.det(S) == 0:
        # raise ValueError("The matrices T and/or S are not invertible.")
        return -1
    
    # Compute the inverse of T
    T_inv = np.linalg.inv(T)

    # Perform the matrix transformation; use @ for better readability
    transformed_matrix = np.round(T_inv @ A @ S, 3)
    
    return transformed_matrix.tolist()

There’s no video solution available yet 😔, but you can be the first to submit one at: GitHub link.

Your Solution

Output will be shown here.