How to Transpose a Matrix in C

How to Transpose a Matrix in C

4 mins read71 Views Comment
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Jul 11, 2024 11:10 IST

Ever worked with matrices in math? If so, you might have come across the term ‘transpose’. But how do we achieve this in the C programming language? This article breaks down the concept of matrix transposition in C, making it easy for anyone to grasp. Curious to learn how? Let’s dive in!

transpose of a matrix in C

 

Transpose of a Matrix is a process of switching its rows and columns. Transpose of a matrix changes the position of the elements of the matrix, but the matrix properties will remain the same.

In simple terms, the transpose of a matrix is interchanging rows and columns. If A is any matrix, then the transpose of the matrix is given by AT.

Must Check: What is C Programming?

Must Check: Types of Matrix

Representation

If A is any matrix of order m x n, then A’s transpose will be n x m.

A = [aij]m x n, then AT = A' = [aij]n x m.

Let’s take an example to get a better understanding of the Transpose of a Matrix.

2023_08_transpose-of-matrix-example.jpg

In this article, we will discuss different methods to transpose how to transpose a matrix in C programming.

Let’s start with the nested for loop.

Transpose of a Matrix using Nested for Loop


 
#include<stdio.h>
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int transpose[3][3];
// Transposing the matrix
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
transpose[j][i] = matrix[i][j]; // Swapping rows with columns
}
}
// Printing the transposed matrix
printf("Transposed Matrix:\n");
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}
return 0;
}
Copy code

Output

2023_08_example-transpose-of-a-matrix-1.jpg

In the above example, we have done the transposition only for a single matrix (i.e., we have defined the matrix). Now let’s generalize the above example. i.e., now we will take the input from the users using the same nested for loop.


 
#include<stdio.h>
int main() {
int m, n;
// Get matrix dimensions from user
printf("Enter the number of rows and columns: ");
scanf("%d %d", &m, &n);
int matrix[m][n], transpose[n][m];
// Input matrix values
printf("Enter matrix elements:\n");
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Transposing using nested loops
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
transpose[j][i] = matrix[i][j];
}
}
// Display the transposed matrix
printf("Transposed Matrix:\n");
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}
return 0;
}
Copy code
Matrix Multiplication in C
Matrix Multiplication in C
A matrix is a collection of numbers organized in rows and columns. Matrices can be manipulated using operations like Addition, Subtraction, and Multiplication. Multiplying two matrices is only possible when...read more
Matrix Multiplication: A Beginner’s Guide to Understand and Implement
Matrix Multiplication: A Beginner’s Guide to Understand and Implement
Matrix multiplication is a binary operation whose output is also a binary operation. If A and B are two matrices of order m x n and n x p, then the order of the output matrix will...read more
All About Skew Symmetric Matrix
All About Skew Symmetric Matrix
A skew-symmetric matrix is a square matrix whose transpose is equal to its negative. In other words, it is a matrix that satisfies the condition A^T = -A. This type...read more

Now, we will discuss one another method to transpose a matrix in C programming.

Recommended online courses

Best-suited C / C++ courses for you

Learn C / C++ with these high-rated online courses

4.24 K
6 weeks
475
6 weeks
– / –
45 hours
4 K
80 hours
– / –
1 month
– / –
40 hours
– / –
2 months
– / –
1 year
4 K
80 hours

Transpose of a Matrix using Pointers


 
#include<stdio.h>
#include<stdlib.h>
int main() {
int m, n;
// Get matrix dimensions from user
printf("Enter the number of rows and columns: ");
scanf("%d %d", &m, &n);
int **matrix, **transpose;
// Dynamic memory allocation
matrix = (int **)malloc(m * sizeof(int *));
transpose = (int **)malloc(n * sizeof(int *));
for(int i=0; i<m; i++) {
matrix[i] = (int *)malloc(n * sizeof(int));
}
for(int i=0; i<n; i++) {
transpose[i] = (int *)malloc(m * sizeof(int));
}
// Input matrix values
printf("Enter matrix elements:\n");
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
scanf("%d", *(matrix + i) + j);
}
}
// Transposing using pointers
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
*(*(transpose + j) + i) = *(*(matrix + i) + j);
}
}
// Display the transposed matrix
printf("Transposed Matrix:\n");
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
printf("%d ", *(*(transpose + i) + j));
}
printf("\n");
}
// Free allocated memory
for(int i=0; i<m; i++) {
free(matrix[i]);
}
for(int i=0; i<n; i++) {
free(transpose[i]);
}
free(matrix);
free(transpose);
return 0;
}
Copy code
All about Symmetric Matrix
All about Symmetric Matrix
A matrix is a rectangular arrangement of numbers (real or complex) or symbols arranged in rows and columns. The number in the matrix are called the elements, and if the...read more
Difference between Eigenvalue and Eigenvector
Difference between Eigenvalue and Eigenvector
Let A be a square matrix of order ‘n-by-n.’ A scalar k is called a eigenvalue of A, if there exist a non-zero vector v satisfying Av = kv, then...read more
3 Important Types of Vector Norm Used in Machine Learning
3 Important Types of Vector Norm Used in Machine Learning
The length or the magnitude of the vector is known as vector norm or vector magnitude. In mathematics, a function is defined on a vector space that maps each vector...read more

Now, let’s see what we have done in both the above methods.

Explanation

  • User Input: In both methods, we took input from the user.
  • Matrix Input: We then prompt the user to input the matrix values.
  • Transposition:
    • In the first method, we use nested loops to transpose the matrix.
    • In the second method, we utilize pointers to achieve the same.
  • Display: The transposed matrix is then displayed to the user.

Note:

  • Memory Allocation: In the second method, we dynamically allocate memory for the matrix and its transpose using pointers.
  • Memory Deallocation: In the second method, we free the dynamically allocated memory to prevent memory leaks.

Conclusion

Transposition is a process of interchanging rows and columns. It plays an important role in computer graphics (transforming 3D models into 2D models), Data Science (data preprocessing, especially when dealing with a tabular dataset), and cryptography (some algorithms use matrix transposition in the encryption or decryption process).

There are different methods to transpose a matrix in C programming. Here, we have discussed two common methods: Nested For Loops and using pointers.

Hope you will like the article.

Keep Learning!!

Keep Sharing!!

Hello World Program in C
Hello World Program in C
Start your coding journey with the introductory program, i.e., Hello World Program in C. This is one of the most simple but powerful programs that give you the idea of...read more
10 Must-Read C Programming Books of All Time
10 Must-Read C Programming Books of All Time
This list of the top C programming books has been curated from several prestigious publications in computing literature, discussions on C programming communities across Reddit, Y Combinator, and bestsellers on...read more
C programming examples 
C programming examples 
If you want to learn C language by executing programming examples. Then this article offers you 17C programming examples with outputs, so that you can learn fast.
What is Interpreter: Types, Advantages and Disadvantages
What is Interpreter: Types, Advantages and Disadvantages
Interpreter is a type of computer program that directly executes instructions written in a programming or scripting language.
Learn About Array of Structure in C
Learn About Array of Structure in C
Discover how to use array structures in C to organize and store related data. Learn about creating, accessing, and manipulating arrays for efficient data management in your C programs. An...read more
Explore strtok() Function in C
Explore strtok() Function in C
The strtok() function in C is a useful tool for splitting strings into tokens based on a delimiter. With its various parameters, strtok() can help you efficiently parse and manipulate...read more
Guide to tolower() Function in C with Examples
Guide to tolower() Function in C with Examples
Enhance your C programming skills with our detailed guide on how to use toupper() function in C effectively. Enhance your C programming skills with our detailed guide on how to...read more
How to Reverse an Array in C
How to Reverse an Array in C
In C programming, Arrays are a useful data structure. It allows the storage of multiple values in a single variable instead of creating individual variables for each value. They are...read more
Learn to Implement strstr() Function in C
Learn to Implement strstr() Function in C
Discover how to use the Strstr function in the C programming language, including its syntax, parameters, and practical applications. Explore examples and tips to effectively implement Strstr in your code...read more
Concatenate Strings with strcat() Function in C
Concatenate Strings with strcat() Function in C
This article offers a comprehensive explanation of the syntax and implementation of the strcat() function, in addition to providing several examples to aid in understanding its operation. By the end...read more
Compare Strings with strcmp Function in C
Compare Strings with strcmp Function in C
The strcmp function in C is used to compare two strings and determine whether they are equal or not. This article explains the syntax and usage of the strcmp function...read more
Explore toupper() Function in C with Examples
Explore toupper() Function in C with Examples
The toupper() function takes a single character as input and returns the corresponding uppercase character. It is commonly used in conjunction with string manipulation functions to convert entire strings to...read more
All About Strlen() Function in C
All About Strlen() Function in C
Unveil the strlen() function in C programming, diving deep into its syntax, practical implementations, and code samples. Learn how to effectively utilise strlen() to determine string lengths, manipulate strings, and...read more
Understanding Strchr() Function in C
Understanding Strchr() Function in C
This blog explains the strchr() Function in C programming with the help of examples. Let’s understand!This blog explains the strchr() Function in C programming with the help of examples. Let’s...read more
strcpy() Function in C
strcpy() Function in C
Uncover the versatility of the strcpy() function in C programming, exploring its syntax, practical applications, and code examples. Learn how strcpy() efficiently copies strings, manipulate substrings, and master string operations...read more

FAQs

What is matrix transposition in C?

Matrix transposition is the process of converting all the rows of a given matrix into columns and vice versa. In C, this can be done by swapping the matrix elements matrix[i][j] with matrix[j][i] in a nested loop structure.

How do I initialize a matrix in C for transposition?

You can initialize a matrix in C using a two-dimensional array, like int matrix[rows][columns];. Fill this matrix with values before transposing.

What is the basic algorithm to transpose a matrix in C?

1. Iterating over each row and column of the matrix. 2. Swapping the elements at indices [i][j] with [j][i]. Note-This approach works well for square matrices. For non-square matrices, you may need a temporary matrix to hold the transposed values.

How can I transpose a non-square matrix in C?

For a non-square matrix, you need a separate matrix to store the transposed matrix because the dimensions will change. Initialize a new matrix with flipped dimensions (rows as columns and vice versa) and copy elements accordingly.

Are there any library functions in C to help with matrix transposition?

Standard C doesn't provide specific library functions for matrix transposition. You'll need to implement the logic manually or use third-party libraries or frameworks that offer matrix operations.

About the Author
author-image
Vikram Singh
Assistant Manager - Content

Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio