In this post I will show you guys how to transpose a matrix using raw python code. The transpose
of a matrix
can be obtained by reflecting the elements along its main diagonal. Repeating the process on the transposed matrix returns the elements to their original position. Hence, Transposing the matrix twice returns the same matrix;
.
Note that, during the operation number of rows and columns are swapped;
. for example:
T(x) – Takes a single argument as a matrix in the form of a list or list of lists (1st degree nested lists) only and performs the transpose operation. As described above, please note that T(T(x)) == x
def T(x):
''' Takes a single argument as a matrix in the form of a list or list of lists only and performs the transpose operation'''
#If the matrix is a simple list or a vector.
if type(x[0]) in [int,float]:
n = 0
g = []
for i in x:
y = []
y.append(x[n])
g.append(y)
n = n + 1
return g
#if matrix is a 1st degree nested list with len(list[0]) == 0.
#note it is indexed to zero because to qualify as a mathematical matrix it needs to be consistent in its dimensions!
elif len(x[0]) == 1:
g = []
g = zip(*x)
o = 0
for i in g:
g[o] = list(g[o])
o += 1
return g[0]
else:
g = []
g = zip(*x)
o = 0
for i in g:
g[o] = list(g[o])
o += 1
return g
Comments