Write your code: Matrix transpose
Contents
Write your code: Matrix transpose#
Write functions that return the transpose of a matrix A.
Rules#
Function returns an numpy array.
You must not use any external function to calculate the transpose.
Function should work for square and non-square matrix.
Useful Links#
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]])
def get_transpose(A):
# write your function here
get_transpose(A)
File "/tmp/ipykernel_1959/1770882093.py", line 5
get_transpose(A)
^
IndentationError: expected an indented block
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)