Search code examples
matrixsquare

I need to convert a 3 column array into a square matrix?


I am looking to convert my data to a square matrix:

image


Solution

  • Say your input is a list; you can then convert it to a list of lists (i.e., a proxy to a matrix) with list comprehension:

    >>> x = [0, 5, 10, 5, 0, 2, 10, 2, 0]
    >>> [x[3*k:3*k+3] for k in range(3)]
    [[0, 5, 10], [5, 0, 2], [10, 2, 0]]
    

    To help you parse the line: you are building a list by iterating over k from 0 to 2, where each element will be a slice of x that starts from index 3*k and ends at index 3*k+3. Thus, your list is [x[0:3], x[3:6], x[6:9]].

    That said, it's much better to use numpy for all such needs. There, you would do:

    >>> import numpy as np
    >>> x = np.array([0, 5, 10, 5, 0, 2, 10, 2, 0])
    >>> x.reshape(3, 3)
    array([[ 0,  5, 10],
           [ 5,  0,  2],
           [10,  2,  0]])
    

    The reshape() function converts your 1D array into the requested 2D matrix.