If I have this matrix, for example:
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
And I want to transpose it over the secondary diagonal, without touching the first row and first column. It would look like this:
matrix = [[1, 2, 3, 4],
[5, 16, 12, 8],
[9, 15, 11, 7],
[13, 14, 10, 6]]
This is what I've tried, but it doesn't change the matrix:
for i in range(1, 4):
for j in range(1, 4):
temp = copy.deepcopy(matrix[i][j])
matrix[i][j] = matrix[4-j][4-i]
matrix[4-j][4-i] = temp
Your code does not work because you are swapping TWO times each pair of variables, building again the same matrix.
Also, you don't need the copy.deepcopy
call for a matrix of integers, and you reference a table
variable which is undefined
# Working code
for i in range(1, 4):
for j in range(1, 4 - i):
matrix[i][j], matrix[4 - j][4 - i] = matrix[4 - j][4 - i], matrix[i][j]