0

I have a matrix-style array, that (hypothetically) looks like this:

mat = [[0,2,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
imat = mat
for i in xrange(4):
    for j in xrange(4):
        imat[j][i] = mat[i][j]
for i in xrange(4):
    for j in xrange(4):
        imat[j][i] = mat[i][j]

The code basically switches the row/column from "mat" to "imat".

The results: mat: [[0, 2, 0, 0], [2, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] imat: [[0, 2, 0, 0], [2, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Could anyone tell me why the array items are duplicating like this?
Also, if there is a more efficient way to do this operation, that would also be appreciated.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
bcdan
  • 1,438
  • 1
  • 12
  • 25

2 Answers2

1

The problem is in this line:

imat = mat

Instead you should do this, to allocate a new 4x4 matrix at the beginning:

imat = [[0]*4 for _ in xrange(4)]

What's happening is that you didn't initialize imat correctly, you only assigned a reference to mat so both objects are one and the same, so no modification is being performed. Also, a much simpler alternative for transposing a matrix would be:

imat = [list(m) for m in zip(*mat)]
Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

Also, if there is a more efficient way to do this operation, that would also be appreciated.

Yes, it's called a matrix transpose operation, which in Python is done using the builtin function zip() with the *-unpacking:

imat = zip(*mat)

As to why your current code doesn't work, @Óscar López has it right, doing imat = mat does not create a new copy of the matrix.

Lie Ryan
  • 62,238
  • 13
  • 100
  • 144