Transpose a Matrix in Python

Matrix Transpose in Python

Python 2:

>>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
>>> zip(*theArray)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]

Python 3:

>>> [*zip(*theArray)]
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]

Transpose Of Matrix in Python

You need to install numpy in order to import it
Numpy transpose returns similar result when

applied on 1D matrix

import numpy  
mymatrix=[[1,2,3],[4,5,6]]
print(mymatrix)
print("\n")
print(numpy.transpose(mymatrix))

Basic matrix transpose in python

Your problem is two fold:

1- B was a label on matrix A, that is every modification to A, also modified B

2- B was local to the transpose function, and could not be accessed outside

A = [[1, 1, 1, 1], 
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]]

def TS (A):
B = [row[:] for row in A] # make a copy of A, not assigning a new label on it.
for i in (range(len(A))):
for j in (range(len(A))):
B[i][j] = A[j][i]
return B

B = TS(A)

for i in range(len(A)):
for j in range(len(A)):
print(B[i][j], " ", end='')
print()

output:

1  2  3  4  
1 2 3 4
1 2 3 4
1 2 3 4

python matrix transpose and zip

question answers:

>>> import numpy as np
>>> first_answer = np.transpose(a)
>>> second_answer = [list(i) for i in zip(*a)]

thanks to afg for helping out

Transpose only the matrix values with numpy if multiple of 3

You need to convert the mask M % 3 == 0 to indices. Something like this should work:

M = M.T
i, j = np.where(M % 3 == 0)
M[i, j] = (3 * j + i)**2

Transposing a 1D NumPy array

It's working exactly as it's supposed to. The transpose of a 1D array is still a 1D array! (If you're used to matlab, it fundamentally doesn't have a concept of a 1D array. Matlab's "1D" arrays are 2D.)

If you want to turn your 1D vector into a 2D array and then transpose it, just slice it with np.newaxis (or None, they're the same, newaxis is just more readable).

import numpy as np
a = np.array([5,4])[np.newaxis]
print(a)
print(a.T)

Generally speaking though, you don't ever need to worry about this. Adding the extra dimension is usually not what you want, if you're just doing it out of habit. Numpy will automatically broadcast a 1D array when doing various calculations. There's usually no need to distinguish between a row vector and a column vector (neither of which are vectors. They're both 2D!) when you just want a vector.

Transposing matrix twice using classes without numpy

You can create a new Matrix object in transpose and return that after printing its content.
For convenience I moved your printing code to a method for converting the matrix to a string (Note that a method called __repr__ will be implicit called by print).
Code:

from copy import deepcopy

class Matrix:
def __init__(self, rows):
self.rows = rows[:]

def transpose(self):
copy = deepcopy(self.rows)
transposed = [[copy[j][i] for j in range(len(copy))] for i in range(len(copy[0]))]
transposed_matrix = Matrix(transposed)
print(transposed_matrix)
return transposed_matrix

def __repr__(self):
matrix = ''
for element in self.rows:
for i in element:
matrix += '%2d' % ((i))
matrix += ' '
matrix = matrix[:-1]
matrix += '\n'
return matrix

Additional improvements:

  • in transpose you can change the matrix transposition to transposed = list(map(list, zip(*self.rows)))
  • use format string instead of '%2d' % ((i)) -> f'{i:2}'
  • join is very helpful for formatting the matrix:
    return '\n'.join(' '.join(f'{i:2}' for i in row) for row in self.rows)

Now the full code looks like this

class Matrix:
def __init__(self, rows):
self.rows = rows[:]

def transpose(self):
transposed = list(map(list, zip(*self.rows)))
transposed_matrix = Matrix(transposed)
print(transposed_matrix)
return transposed_matrix

def __repr__(self):
return '\n'.join(' '.join(f'{i:2}' for i in row) for row in self.rows)


Related Topics



Leave a reply



Submit