Infer Matrix

The infer_matrix function is a powerful tool for determining the matrix representation of a linear transformation. This function is particularly useful in the fields of programming and data science, where understanding and manipulating transformations is crucial.

Function Definition

The infer_matrix function is defined as follows:

def infer_matrix(n, transformation):
    def standard_basis_vector(i):
        return tuple(1 if i==j else 0 for j in range(1,n+1))         #1
    standard_basis = [standard_basis_vector(i) for i in range(1,n+1)]#2
    cols = [transformation(v) for v in standard_basis]               #3
    return tuple(zip(*cols))                                         #4

Explanation

  1. Standard Basis Vector: The function standard_basis_vector(i) creates the ith standard basis vector as a tuple. This vector contains a one in the ith coordinate and zeroes in all other coordinates.

  2. Standard Basis: The standard_basis is a list of N vectors, where N is the dimension of the input vectors. This list is constructed using the standard basis vectors.

  3. Transformation Application: The cols list is created by applying the given linear transformation to each vector in the standard basis. This step defines the columns of the resulting matrix.

  4. Matrix Reshaping: Finally, the function returns the matrix as a tuple of rows, which is achieved by transposing the list of columns.

Usage Examples

Rotation Transformation

The infer_matrix function can be tested with a linear transformation such as rotate_z_by(pi/2). This transformation rotates vectors around the z-axis by 90 degrees.

>>> from transforms import rotate_z_by
>>> from math import pi
>>> infer_matrix(3, rotate_z_by(pi/2))
((6.123233995736766e−17, −1.0, 0.0), (1.0, 1.2246467991473532e−16, 0.0), (0, 0, 1))

Composition of Transformations

The function can also be used to find the matrix corresponding to a composition of linear transformations. For example, given a composed transformation compose_a_b, the matrix can be inferred and compared to the matrix product AB:

>>> infer_matrix(3, compose_a_b)
((0, 3, 1), (1, 2, 0), (1, 1, 0))
>>> matrix_multiply(a, b)
((0, 3, 1), (1, 2, 0), (1, 1, 0))

Projection Transformation

Another example is projecting 3D vectors onto the x,y plane. This transformation can be implemented as a Python function and its matrix representation can be inferred:

>>> def project_xy(v):
...     x, y, z = v
...     return (x, y)
...
>>> infer_matrix(3, project_xy)
((1, 0, 0), (0, 1, 0))

In this case, the dimension of the input vectors is specified as an argument to ensure the correct standard basis vectors are used. The project_xy function then outputs 2D vectors, which form the columns of the resulting 2×3 matrix.