- Print the original matrix
- Print the transpose matrix
- Print the product of the original matrix and the transpose
Transpose of a Matrix
To “transpose” a matrix, swap the rows and columns. We put a “T” in the top right-hand corner to mean transpose:
How to Multiply Matrices
A Matrix is an array of numbers:
A Matrix
(This one has 2 Rows and 3 Columns)
To multiply a matrix by a single number is easy:
2×4=8 | 2×0=0 |
2×1=2 | 2×-9=-18 |
We call the number (“2” in this case) a scalar, so this is called “scalar multiplication”.
Multiplying a Matrix by Another Matrix
But to multiply a matrix by another matrix we need to do the “dot product” of rows and columns … what does that mean? Let us see with an example:
To work out the answer for the 1st row and 1st column:
The “Dot Product” is where we multiply matching members, then sum up:
(1, 2, 3) • (7, 9, 11) = 1×7 + 2×9 + 3×11 = 58
We match the 1st members (1 and 7), multiply them, likewise for the 2nd members (2 and 9) and the 3rd members (3 and 11), and finally sum them up.
Here it is for the 1st row and 2nd column:
(1, 2, 3) • (8, 10, 12) = 1×8 + 2×10 + 3×12 = 64
We can do the same thing for the 2nd row and 1st column:
(4, 5, 6) • (7, 9, 11) = 4×7 + 5×9 + 6×11 = 139
And for the 2nd row and 2nd column:
(4, 5, 6) • (8, 10, 12) = 4×8 + 5×10 + 6×12 = 154
And we get:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
import java.io.*; public class Transpose_Multiply { public static void main()throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); int m, n; System.out.println("Enter the number of rows:"); m = Integer.parseInt(r.readLine()); System.out.println("Enter the number of columns:"); n = Integer.parseInt(r.readLine()); int a[][] = new int[m][n], b[][] = new int[n][m], i, j, s=0, k; System.out.println("Enter the values for the array:"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { a[i][j] = Integer.parseInt(r.readLine()); b[j][i] = a[i][j]; } } int c[][] = new int[m][m]; for(i=0;i<m;i++) { for(j=0;j<m;j++) { s=0; for(k=0;k<n;k++) { s+=a[i][k]*b[k][j]; } c[i][j] = s; } } //Printing the various arrays System.out.println("Original Array:"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { System.out.print(a[i][j]+"t"); } System.out.println(); } //Printing the various arrays System.out.println("Transpose Array:"); for(i=0;i<n;i++) { for(j=0;j<m;j++) { System.out.print(b[i][j]+"t"); } System.out.println(); } //Printing the various arrays System.out.println("Multiplied Array:"); for(i=0;i<m;i++) { for(j=0;j<m;j++) { System.out.print(c[i][j]+"t"); } System.out.println(); } } } |
Leave a Reply
You must be logged in to post a comment.