Skip to content

Commit e109784

Browse files
authored
Add files via upload
1 parent 6bbf627 commit e109784

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import java.util.Arrays;
2+
3+
public class Matrix_Exponentiation {
4+
5+
/*Matrix Exponentiation Algorithm
6+
7+
Problem (informal): Given a matrix M, find the product: M^n = M x M x ... x M
8+
9+
Algorithm: Brute force algorithm for repeated multiplication
10+
11+
Complexity:
12+
* Time - O(n*i*j*k) where a has dimensions i x j and b has dimensions j x k to compute M^n
13+
* Space - O(i*j) where M has i rows and j columns
14+
15+
Functions Defined:
16+
* matrix_multiply() - returns matrix product of matrices a and b
17+
* matrix_exponentation() - returns M^n via repeated multiplication of M for square matrix M
18+
19+
*/
20+
21+
22+
23+
public static void main(String[] args){
24+
int[][] a = {{1, 2, 3, 2}, {2, 3, 4, 8}, {4, 5, 3, 6}}; //3 x 4
25+
int[][] b = {{6, 1, 4}, {9, 0, 6}, {6, 4, 5}, {3, 1, 1}}; // 4 x 3
26+
int[][] m = matrix_multiply(a, b);
27+
System.out.println(Arrays.deepToString(m));
28+
29+
//testing staticness with multiplication with identity
30+
int[][] identity = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
31+
int[][] m2 = matrix_multiply(m, identity);
32+
System.out.println(Arrays.deepToString(m2));
33+
34+
//matrix exponentiation
35+
m2 = matrix_exponentiation(m2, 2);
36+
37+
System.out.println(Arrays.deepToString(m2));
38+
}
39+
40+
//assumes that matrix b has j rows and a has j columns
41+
//O(ijk) where a has dimensions i x j and b has dimensions j x k
42+
public static int[][] matrix_multiply(int[][] a, int[][] b){
43+
int[][] m = new int[a.length][b[0].length];
44+
for(int i=0;i<a.length;i++){
45+
for(int j = 0; j < b[0].length;j++){
46+
//m[i][j] is product of ith row of A and jth column of B
47+
int sum = 0;
48+
for(int k = 0; k < b.length; k++){
49+
sum+= a[i][k]*b[k][j];
50+
}
51+
m[i][j] = sum;
52+
}
53+
}
54+
return m;
55+
}
56+
57+
//O(n*ijk) where a has dimensions i x j and b has dimensions j x k to compute M^n
58+
public static int[][] matrix_exponentiation(int[][] m, int n){
59+
while(n-- > 1){
60+
m = matrix_multiply(m, m);
61+
}
62+
return m;
63+
}
64+
}

0 commit comments

Comments
 (0)