D
David
Should the following line work for defining a matrix with zeros?
c= [[0]*col]*row
where "col" is the number of columns in the matrix and "row" is of
course the number of rows.
If this a valid way of initializing a matrix in Python 3.2.1, then it
appears to me that a bug surfaces in Python when performing this line:
c[j] = c[j] + a[k] * b[k][j]
It writes to the jth column rather than just the i,j cell.
I'm new at Python and am not sure if I'm just doing something wrong if
there is really a bug in Python. The script works fine if I
initialize the matrix with numpy instead:
c = np.zeros((row,col))
So, I know my matrix multiply algorithm is correct (I know I could use
numpy for matrix multiplication, this was just to learn Python).
I've attached my source code below.
TIA,
David
-----
#!python
# dot.py - Matrix multiply in matricies: [c] = [a] *
import numpy as np
a = [[3, 7], [-2, 1], [2, 4]]
b = [[2, 1, -3, 1], [4, 3, -2, 3]]
print("a = {0}, b = {1}".format(a,b))
row = len(a)
col = len(b[0])
#c = np.zeros((row,col)) # <----- Correct results when using this
line
c= [[0]*col]*row # <----- Incorrect results when using
this line
print(c)
for i in range(row): # Index into rows of [a]
for j in range(col): # Index into columns of
c[j] = 0
for k in range(len(b)): # Index into columns of [a] and rows of
print("c[{0}][{1}] + a[{2}][{3}] * b[{4}][{5}] = {6} + {7} *
{8}".format(i,j,i,k,k,j,c[j],a[k],b[k][j]))
c[j] = c[j] + a[k] * b[k][j]
print(c)
c= [[0]*col]*row
where "col" is the number of columns in the matrix and "row" is of
course the number of rows.
If this a valid way of initializing a matrix in Python 3.2.1, then it
appears to me that a bug surfaces in Python when performing this line:
c[j] = c[j] + a[k] * b[k][j]
It writes to the jth column rather than just the i,j cell.
I'm new at Python and am not sure if I'm just doing something wrong if
there is really a bug in Python. The script works fine if I
initialize the matrix with numpy instead:
c = np.zeros((row,col))
So, I know my matrix multiply algorithm is correct (I know I could use
numpy for matrix multiplication, this was just to learn Python).
I've attached my source code below.
TIA,
David
-----
#!python
# dot.py - Matrix multiply in matricies: [c] = [a] *
import numpy as np
a = [[3, 7], [-2, 1], [2, 4]]
b = [[2, 1, -3, 1], [4, 3, -2, 3]]
print("a = {0}, b = {1}".format(a,b))
row = len(a)
col = len(b[0])
#c = np.zeros((row,col)) # <----- Correct results when using this
line
c= [[0]*col]*row # <----- Incorrect results when using
this line
print(c)
for i in range(row): # Index into rows of [a]
for j in range(col): # Index into columns of
c[j] = 0
for k in range(len(b)): # Index into columns of [a] and rows of
print("c[{0}][{1}] + a[{2}][{3}] * b[{4}][{5}] = {6} + {7} *
{8}".format(i,j,i,k,k,j,c[j],a[k],b[k][j]))
c[j] = c[j] + a[k] * b[k][j]
print(c)