TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Python Transpose Matrix

Python Transpose Matrix for beginners and professionals with programs on basics, controls, loops, functions, native data types etc.

<< Back to PYTHON

Python Program to Transpose a Matrix

In 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 matrix

If 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 matrix

Now, 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]





Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf