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 multiply matrix in Python

2 Answers

0 votes
from sys import stdout


def print_list(list2d, n):
    for ii in range(n):
        for jj in range(n):
            stdout.write("%4d" % list2d[ii][jj])
        stdout.write("\n")


def calc(aa, bb, ii, jj, n):
    sum_ab = 0

    for x in range(n):
        sum_ab += aa[ii][x] * bb[x][jj]

    return sum_ab


a = [[1, 8, 5], [6, 7, 1], [8, 7, 6]]
b = [[4, 8, 1], [6, 5, 3], [4, 6, 5]]
c = [[0]*3 for _ in range(3)]
size = 3

print_list(a, size)
stdout.write("\n")
print_list(b, size)
stdout.write("\n")

# c[0, 0] = (a[0, 0] * b[0, 0]) + (a[0, 1] * b[1, 0]) + (a[0, 2] * b[2, 0])

for i in range(size):
    for j in range(size):
        c[i][j] = calc(a, b, i, j, size)

print_list(c, size)


'''
run:

   1   8   5
   6   7   1
   8   7   6

   4   8   1
   6   5   3
   4   6   5

  72  78  50
  70  89  32
  98 135  59
 
'''

 



answered Feb 28, 2016 by avibootz
edited Feb 28, 2016 by avibootz
0 votes
from sys import stdout


def print_list(list2d, n):
    for ii in range(n):
        for jj in range(n):
            stdout.write("%4d" % list2d[ii][jj])
        stdout.write("\n")


def multiple_matrix(aa, bb, cc, n):
    for i in range(n):
        for j in range(n):
            cc[i][j] = 0
            for k in range(size):
                cc[i][j] = cc[i][j] + aa[i][k] * bb[k][j]


a = [[1, 8, 5], [6, 7, 1], [8, 7, 6]]
b = [[4, 8, 1], [6, 5, 3], [4, 6, 5]]
c = [[0]*3 for _ in range(3)]
size = 3

print_list(a, size)
stdout.write("\n")
print_list(b, size)
stdout.write("\n")

# c[0, 0] = (a[0, 0] * b[0, 0]) + (a[0, 1] * b[1, 0]) + (a[0, 2] * b[2, 0])

multiple_matrix(a, b, c, size)

print_list(c, size)


'''
run:

   1   8   5
   6   7   1
   8   7   6

   4   8   1
   6   5   3
   4   6   5

  72  78  50
  70  89  32
  98 135  59
 
'''

 



answered Feb 28, 2016 by avibootz

Related questions

1 answer 89 views
1 answer 103 views
1 answer 101 views
1 answer 130 views
1 answer 128 views
1 answer 130 views
...