Python matrices - Concatenate

Asked

Viewed 1,192 times

0

Hello, I have two matrices and I would like to concatenate them, that is, put in a third matrix the matrices A and B one next to the other, in case form a matrix 3x6, but using a loop (command "for") for this. Could you help me? Thank you.

matriz_a = [
    [0, 0, 1],
    [0, 1, 0],
    [1, 0, 1]
]

print(matriz_a)


matriz_b = [
        [2, 2, 3],
        [3, 2, 2],
        [3, 3, 3]
    ]

print(matriz_b)
  • 2

    "side by side" - it would be clearer if you could exemplify how this resulting matrix would be taking into account the matrix A and B of the question.

  • I edited explaining correctly now, thank you!

2 answers

3


You can use the native function zip:

def matrix_union(A, B):
    for a, b in zip(A, B):
        yield [*a, *b]

The return of the function will be a generator in which each line will be the junction of the lines of matrix A with matrix B.

For example:

A = [
    [0, 0, 1],
    [0, 1, 0],
    [1, 0, 1]
]

B = [
    [2, 2, 3],
    [3, 2, 2],
    [3, 3, 3]
]

print(list(matrix_union(A, B)))

See working on Repl.it | Ideone | Github GIST

Will generate:

[
    [0, 0, 1, 2, 2, 3], 
    [0, 1, 0, 3, 2, 2], 
    [1, 0, 1, 3, 3, 3]
]

0

You don’t even have to wear one for. You can do the following:

matriz_a = [
    [0, 0, 1],
    [0, 1, 0],
    [1, 0, 1]
]

matriz_b = [
        [2, 2, 3],
        [3, 2, 2],
        [3, 3, 3]
    ]

matriz_c = [*matriz_a, *matriz_b]  
print(matriz_c)
# [[0, 0, 1], [0, 1, 0], [1, 0, 1], [2, 2, 3], [3, 2, 2], [3, 3, 3]]

The operator * unpacking each of its matrices (lists).

If I still wanted to wear one for and no other method could do the following:

matriz_c = []

for matriz in (matriz_a, matriz_b):
    for elemento in matriz:
        matriz_c.append(elemento)        

print(matriz_c)
#  [[0, 0, 1], [0, 1, 0], [1, 0, 1], [2, 2, 3], [3, 2, 2], [3, 3, 3]]
  • Hi, thank you in advance. It turns out that I would really need to use the go command, but it would have to become a 3x6 matrix, where actually a and b would be next to each other. I don’t think I explained it correctly...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.