C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python Program to Transpose a MatrixIn this tutorial, we will write a Python program to get the transpose of matrix and print the result in output. Before writing the Python program, let's first look at the overview of the transpose of a matrix. Transpose of a matrixIf you change the rows of a matrix with the column of the same matrix, it is known as the transpose of a matrix. It is denoted as X'. For example: The element at ith row and jth column in X will be placed at jth row and ith column in X'. Example: Suppose we have given following matrix A: A = [[5, 4, 3] [2, 4, 6] [4, 7, 9] [8, 1, 3]] At would be the transpose of above given matrix i.e., A[i][j] = At[j][i] and therefore At should be: At = [5, 2, 4, 8] [4, 4, 7, 1] [3, 6, 9, 3] Python program for transpose of a matrixNow, we will write a Python program for the transpose of an input given matrix where we perform the operation as we have performed in the above-given example. To perform the transpose operation on the matrix, we will use the nested for loop method. Let's understand the use and implementation of this method through the following example. Example: Look at the following Python program: # Define a matrix A A = [[5, 4, 3], [2, 4, 6], [4, 7, 9], [8, 1, 3]] # Define an empty matrix of reverse order transResult = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] # Use nested for loop on matrix A for a in range(len(A)): for b in range(len(A[0])): transResult[b][a] = A[a][b] # store transpose result on empty matrix # Printing result in the output print("The transpose of matrix A is: ") for res in transResult: print(res) Output: The transpose of matrix A is: [5, 2, 4, 8] [4, 4, 7, 1] [3, 6, 9, 3]
Next TopicPython Alphabetic Order
|