Danilo Santos
Danilo Santos

Reputation: 1

How to insert a series of numbers into a matrix?

As an example, I have a 9x9 matrix:

x=[
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
]

and I want to insert a series of numbers like the example:

aux=900000001051200030000980000680740000730000908010058670008100000002007090190004060

I want to be able to put each digit into an individual position of the matrix, but I am a little stuck on attacking this problem.

Upvotes: 0

Views: 1155

Answers (2)

ABarrier
ABarrier

Reputation: 952

The following code by using Python 3.7 will do the job for you:

if __name__ == "__main__":
    # size of the array n x n
    n = 9

    # the n x n array
    x = [[0]*n]*n

    # the input number converted as a string
    aux = "900000001051200030000980000680740000730000908010058670008100000002007090190004060"

    k = 0
    for i in range(0,n):
        for j in range(0,n):
            x[i][j] = aux[k]
            k = k + 1

then for printing the matrix x you do:

import numpy as np

# print the modified array x
print(np.matrix(x))

which gives the output:

[['9' '0' '0' '0' '0' '0' '0' '0' '1']
 ['0' '5' '1' '2' '0' '0' '0' '3' '0']
 ['0' '0' '0' '9' '8' '0' '0' '0' '0']
 ['6' '8' '0' '7' '4' '0' '0' '0' '0']
 ['7' '3' '0' '0' '0' '0' '9' '0' '8']
 ['0' '1' '0' '0' '5' '8' '6' '7' '0']
 ['0' '0' '8' '1' '0' '0' '0' '0' '0']
 ['0' '0' '2' '0' '0' '7' '0' '9' '0']
 ['1' '9' '0' '0' '0' '4' '0' '6' '0']]

Upvotes: 1

Poojan
Poojan

Reputation: 3519

  • This oneliner works by splitting by 9 and mapping to integers again.
  • for i in range(0, len(str(aux)), 9) This will iterate over chunks of size 9.
  • list(map(int, aux[i,i+9])) This will map each character from string to int and create list of it. You can see map function in python for more info.
  • Above two steps combined in list comprehension will give you list of lists.
aux=900000001051200030000980000680740000730000908010058670008100000002007090190004060 # assumption 81 digit number or string ?
m = [list(map(int, str(aux)[i:i+9])) for i in range(0, len(str(aux)), 9)]
print(m)
  • Output
[[9, 0, 0, 0, 0, 0, 0, 0, 1],
 [0, 5, 1, 2, 0, 0, 0, 3, 0],
 [0, 0, 0, 9, 8, 0, 0, 0, 0],
 [6, 8, 0, 7, 4, 0, 0, 0, 0],
 [7, 3, 0, 0, 0, 0, 9, 0, 8],
 [0, 1, 0, 0, 5, 8, 6, 7, 0],
 [0, 0, 8, 1, 0, 0, 0, 0, 0],
 [0, 0, 2, 0, 0, 7, 0, 9, 0],
 [1, 9, 0, 0, 0, 4, 0, 6, 0]]

Upvotes: 1

Related Questions