Python bug? Indexing to matrices
sturlamolden
sturlamolden at yahoo.no
Tue Jul 12 08:59:12 EDT 2011
On 12 Jul, 07:39, David <davidb... at gmail.com> wrote:
> Should the following line work for defining a matrix with zeros?
>
> c= [[0]*col]*row
No. The rows will be aliased.
This will work:
c = [[0]*col for i in range(row)]
Note that Python lists are not ment to be used as matrices. We have
NumPy or the array module for that.
> 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[i][j] = c[i][j] + a[i][k] * b[k][j]
>
> It writes to the jth column rather than just the i,j cell.
That is due to aliasing.
> 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).
Like so:
np.dot(a,b)
or
ma = np.matrix(a)
mb = np.matrix(b)
a*b
or call BLAS directly:
scipy.linalg.fblas.dgemm
Sturla
More information about the Python-list
mailing list