Solution: Matrix transpose#

Write functions that return the transpose of a matrix A.

Rules#

  1. Function returns an numpy array.

  2. You must not use any external function to calculate the transpose.

  3. Function should work for square and non-square matrix.

Transpose overview#

Consider a matrix \(A\) of order \(j\times i\). The transpose of a matrix \(A\), denoted by \(A^T\), may be constructed by writing the columns of \(A\) as the rows of \(A^T\).

Formally, in the i-th row, j-th column element of \(A^T\) is the j-th row, i-th column element of \(A\):

\[ [A^T]_{i, j} = A_{j,i}\]

Example#

Consider the following matrix \(A\):

\[\begin{split} A = \begin{bmatrix} 1 & 2 & 3\\ 4 & 5 & 6 \end{bmatrix} \end{split}\]

The transpose is:

\[\begin{split} A^T = \begin{bmatrix} 1 & 4\\ 2 & 5 \\ 3 & 6 \end{bmatrix} \end{split}\]

Function Definition#

Solution#

import numpy as np

A = np.array([[4, 7, 3],
              [2, 5, 6]])

Using for loop#

def get_transpose(A):
    m = A.shape[0]
    n = A.shape[1]
    T = np.zeros((n, m))

    for i in range(m):
        for j in range(n):
   
            T[j,i] = A[i,j]

    return T
    
get_transpose(A)
array([[4., 2.],
       [7., 5.],
       [3., 6.]])

Using advanced indexation#

def get_transpose(A):

    m = A.shape[0]
    n = A.shape[1]
    T = np.zeros((n, m))

    i = np.array(range(m)).reshape(m,1)
    j = range(n)
    T[j,i] = A[i,j]

    return T

get_transpose(A)
array([[4., 2.],
       [7., 5.],
       [3., 6.]])

Testing#

Check if your function returns the expected value using the cell below.

import unittest

class UnitTests(unittest.TestCase):
    def setUp(self):
        self.A = np.array([[1, 2, 3],
                           [4, 5, 6],
                           [7, 8, 9]]
                         )
        self.R = np.array([[1, 2, 3]]
                         )
        self.C = np.array([[1],
                           [2],
                           [3]]
                         )                         
    def test_type(self):
        self.assertTrue(isinstance(get_transpose(self.A), np.ndarray), 'The function should return a NumPy array')
    def test_square(self):
        self.assertTrue((get_transpose(self.A)==np.array([[1, 4, 7],[2, 5, 8],[3, 6, 9]])).all())
    def test_row(self):
        self.assertTrue((get_transpose(self.R)==np.array([[1],[2],[3]])).all())
    def test_column(self):
        self.assertTrue((get_transpose(self.C)==np.array([[1,2,3]])).all())
unittest.main(argv=[''], verbosity=2,exit=False)
test_column (__main__.UnitTests) ... 
ok
test_row (__main__.UnitTests) ... 
ok
test_square (__main__.UnitTests) ... 
ok
test_type (__main__.UnitTests) ... 
ok

----------------------------------------------------------------------
Ran 4 tests in 0.005s

OK
<unittest.main.TestProgram at 0x7fd068060e90>