Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,960 questions

51,902 answers

573 users

How to add two matrices in Python

3 Answers

0 votes
matrix1 = [[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]]

matrix2 = [[1, 1, 1],
           [1, 1, 1],
           [1, 1, 1]]

result = [[0, 0, 0],
          [0, 0, 0],
          [0, 0, 0]]

for i in range(len(matrix1)):
    for j in range(len(matrix1[0])):
        result[i][j] = matrix1[i][j] + matrix2[i][j]

for row in result:
    for val in row:
        print('{:3}'.format(val), end="")
    print()
 


'''
run:
 
  2  3  4
  5  6  7
  8  9 10
 
'''

 



answered May 31, 2017 by avibootz
edited Nov 26, 2023 by avibootz
0 votes
matrix1 = [[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]]
 
matrix2 = [[1, 1, 1],
           [1, 1, 1],
           [1, 1, 1]]

result = [[matrix1[i][j] + matrix2[i][j] for j in range(len(matrix1[0]))] 
                                         for i in range(len(matrix1))]
 
for row in result:
    for val in row:
        print('{:3}'.format(val), end="")
    print()
  
  
  
'''
run:
  
  2  3  4
  5  6  7
  8  9 10
  
'''

 



answered May 31, 2017 by avibootz
edited Nov 26, 2023 by avibootz
0 votes
matrix1 = [[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]]
 
matrix2 = [[1, 1, 1],
           [1, 1, 1],
           [1, 1, 1]]

result = [map(sum, zip(*t)) for t in zip(matrix1, matrix2)]
 
for row in result:
    for val in row:
        print('{:3}'.format(val), end="")
    print()
  
  
  
'''
run:
  
  2  3  4
  5  6  7
  8  9 10
  
'''

 



answered Nov 26, 2023 by avibootz

Related questions

1 answer 214 views
1 answer 204 views
204 views asked Jul 7, 2021 by avibootz
1 answer 154 views
154 views asked May 24, 2017 by avibootz
1 answer 140 views
140 views asked May 24, 2017 by avibootz
1 answer 249 views
249 views asked May 24, 2017 by avibootz
1 answer 161 views
161 views asked May 24, 2017 by avibootz
1 answer 146 views
146 views asked May 23, 2017 by avibootz
...