I am making a function in python in which when taking a matrix A, it returns a matrix B with swapped rows and columns, example:
if i enter this matrix:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Should return
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
but what I get is:
array([[ 1, 5, 9, 13],
[ 5, 6, 10, 14],
[ 9, 10, 11, 15],
[13, 14, 15, 16]])
I don't understand why, could someone help me understand this error and how can I solve it?
my code:
def transpose(matrix):
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
matrix[i][j] = matrix[j][i]
return matrix
(I can't use default functions like transpose, I have to code)
This line
matrix[i][j] = matrix[j][i]
is your issue.
For example, when i = 1
and j = 2
, you set matrix[1][2]
to 10 because matrix[2][1]
is 10. When you come around the next time to i = 2
and j = 1
, you set matrix[2][1]
to 10 because matrix[1][2]
was set to 10 even though it was originally 7, it doesn't keep a memory of the previous value.
Depending on if you want the function to mutate the original matrix or return a new matrix with changes values (but keep the original) will change how you create this function.
To mutate the original
def transpose(matrix):
matrix2 = numpy.copy(matrix)
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
matrix[i][j] = matrix2[j][i]
return matrix
To return a new array
def transpose(matrix):
matrix2 = numpy.copy(matrix)
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
matrix2[i][j] = matrix[j][i]
return matrix2