Share on Google+Share on Google+

Java Transpose of a matrix

Advertisement
In this Java Tutorial for beginners section, you will learn how to determine the Java transpose of a matrix.

Java Transpose of a matrix

In this section, you will learn how to determine the transpose of a matrix.The transpose of a matrix is formed by interchanging the rows and columns of a matrix such that row i of matrix becomes column i of the transposed matrix. The transpose of A is denoted by AT. Through the following code,the user is allowed to enter the number of rows and columns and the elements to create a matrix. Then using the for loop statements, turn all the rows of the matrix into columns and vice-versa.

Here is the code:

import java.util.*;

public class Transpose {
	public static void main(String[] args) throws Exception {
		int rows, cols;
		int[][] matrix, tmatrix;
		Scanner input = new Scanner(System.in);
		System.out.print("Enter number of rows: ");
		rows = input.nextInt();
		System.out.print("Enter number of columns: ");
		cols = input.nextInt();
		matrix = new int[rows][cols];
		tmatrix = new int[cols][rows];
		System.out.println("Enter elements for Matrix");
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				matrix[i][j] = input.nextInt();
			}
		}
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				tmatrix[i][j] = matrix[j][i];
			}
		}
		System.out.println("Matrix is:");
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				System.out.print(matrix[i][j] + " ");
			}
			System.out.println();
		}
		System.out.println("Its transpose is: ");
		for (int i = 0; i < cols; i++) {
			for (int j = 0; j < rows; j++) {
				System.out.print(tmatrix[i][j] + " ");
			}
			System.out.println();
		}
	}
}

Output:

Enter number of rows: 3
Enter number of columns: 3
Enter elements for matrix:
1
2
3
4
5
6
7
8
9
Matrix is:
1 2 3
4 5 6
7 8 9
Its transpose is:
1 4 7
2 5 8
3 6 9

Advertisements

Advertisement

Posted on: January 15, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.