-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathMatrixMultiplication.java
More file actions
90 lines (75 loc) · 2.37 KB
/
MatrixMultiplication.java
File metadata and controls
90 lines (75 loc) · 2.37 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner ez = new Scanner(System.in);
int w, q;
System.out.println("Enter no of row of a matrix: ");
w = ez.nextInt();
System.out.println("Enter no of col of a matrix: ");
q = ez.nextInt();
Matrix a = new Matrix(w, q);
System.out.println("Enter no of row of b matrix: ");
w = ez.nextInt();
System.out.println("Enter no of col of b matrix: ");
q = ez.nextInt();
Matrix b = new Matrix(w, q);
System.out.println("Enter for a matrix: ");
a.getValues();
System.out.println("Enter for b matrix: ");
b.getValues();
Matrix c = a.multiply(b);
System.out.println("Matrix A multiplied by B:");
c.display();
}
}
class Matrix {
int x, y;
int[][] no;
Scanner ez = new Scanner(System.in);
public Matrix() {
this.x = 0;
this.y = 0;
no = new int[this.x][this.y];
}
public Matrix(int x, int y) {
this.x = x;
this.y = y;
no = new int[this.x][this.y];
}
public void getValues() {
for (int i = 0; i < this.x; i++) {
for (int j = 0; j < this.y; j++) {
System.out.println("Enter [" + i + "," + j + "] no:");
no[i][j] = ez.nextInt();
}
}
}
public static void setIn(Matrix z, int a, int b, int c) {
z.no[a][b] = c;
}
public Matrix multiply(Matrix an) {
Matrix co = new Matrix(this.x, an.y);
if (this.y != an.x) {
System.out.println("Can't multiply");
} else {
for (int a = 0; a < this.x; a++) {
for (int b = 0; b < an.y; b++) {
int sum = 0;
for (int c = 0; c < an.x; c++) {
sum += this.no[a][c] * an.no[c][b];
}
Matrix.setIn(co, a, b, sum);
}
}
}
return co;
}
public void display() {
for (int i = 0; i < this.x; i++) {
for (int j = 0; j < this.y; j++) {
System.out.print(this.no[i][j] + " ");
}
System.out.println();
}
}
}