Add elements of the first matrix to those of the second matrix in Python

Asked

Viewed 720 times

0

There are two matrices with 5 rows and 3 columns, how do I accomplish the sum of the elements of the first matrix and the elements of the second matrix.

For example:

-- 1a matriz --
02 04 06 
08 10 12
14 16 18
20 22 24
26 28 30

-- 2a matriz --
01 03 05
07 09 11
13 15 17
19 21 23
25 27 29

-- Saída --
03 07 11 
15 19 23
27 31 35
39 43 47
51 55 39
Por enquanto meu código está assim, sem a parte que somas os elementos das 
linha = 0
coluna = 0

# -------- Matriz 1 --------
matrizes
mat1A = input().split()
mat1B = input().split()
mat1C = input().split()
mat1D = input().split()
mat1E = input().split() 
# -------- Matriz 2 --------
mat2A = input().split()
mat2B = input().split()
mat2C = input().split()
mat2D = input().split()
mat2E = input().split()

mat3 = [mat1A, mat1B, mat1C, mat1D, mat1E,
        mat2A,mat2B,mat2C,mat2D,mat2E]

for linha in range(len(mat3)):
    for coluna in range(len(mat3[i])):
        print (mat3[linha][coluna], end = "\t")
    print()
  • As I said in my answer to your other matrix question, you can use numpy. After reading the matrices mat1 and mat2 as a numpy.narray, just do mat1 + mat2.

  • I’m still not familiar with library numpy (nor my teacher kkk)

2 answers

1


First, create two auxiliary constants to know how many rows and how many columns the matrices will have. (This step is not necessary, but makes the code easier to understand)

LINHAS = 5
COLUNAS = 3

Once done, read both matrices, converting the values to int in accordance with I’ve already shown you in another answer.

mat1 = []

for i in range(LINHAS):
    mat1.append([int(x) for x in input().split()])

mat2 = []

for i in range(LINHAS):
    mat2.append([int(x) for x in input().split()])

Now just iterate through both matrices, adding up the elements and printing on the screen.

for i in range(LINHAS):
    for j in range(COLUNAS):
        valor_soma = mat1[i][j] + mat2[i][j]
        print('{0:02d} '.format(valor_soma), end='')
    print()

Additional reading (it is important to read the documentation!):

  • explain to me better {0:02d}, although I know it’s part of format

  • @Alexf. The first 0 indicates that there will enter the first parameter passed to function format. The 02d indicates that the parameter is an integer (d) which must occupy 2 digits (2) and that the digit on the left should be a "0" case over space (0).

  • I understand your explanation

0

I did it that way:

Credits: Introduction to Computer Science Python USP/Coursera By Fabio Kon

Sum of matrices

def cria_matriz(n_linhas, n_colunas, valor):
matriz = [] # Lista Vazia para matriz
for x in range(n_linhas):
    #Cria a linha x
    linha = [] # lista vazia para linhas
    for y in range(n_colunas):
        linha.append(valor)

    # Adiciona linha à matriz
    matriz.append(linha)
    
return matriz    

def soma_matrizes(m1, m2):
num_lin = len(m1)
num_col = len(m1[0])

num_linB = len(m2) # Verifica quantidade de linhas
num_colB= len(m2[0]) # Verifica quantidade de colunas
    
if num_lin == num_linB and num_col == num_colB:

    C = cria_matriz(num_lin, num_col, 0) # Chama A função cria_matriz

    for lin in range(num_lin): # Percorre linhas da matriz
        for col in range(num_col): # Percorre colunas da matriz
            C[lin][col] = m1[lin][col] + m2[lin][col]
    return C
else:
    return False

Browser other questions tagged

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