-
Notifications
You must be signed in to change notification settings - Fork 61
/
IdentityMatrix.java
113 lines (105 loc) · 2.01 KB
/
IdentityMatrix.java
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package com.java.matrix;
/*
* Identity Matrix
* ----------------
* If a matrix is a Identity matrix then it should
* follow all the conditions
* 1. It should be square matrix row == column
* 2. All the elements of main diagonal should be 1
* 3. Rest of the elements should be 0.
*
* If any of the above conditions are not satisfied
* then the matrix is not Identity Matrix.
*
* Examples of Identity matrix
* ----------------------------
* 1 0 0
* 0 1 0
* 0 0 1
*
* 1 0 0 0
* 0 1 0 0
* 0 0 1 0
* 0 0 0 1
*
* NOT Identity matrix
* --------------------
* 1 2
* 3 4
*
* 1 1 1
* 1 0 1
* 1 1 1
*
* 1 0 0
* 0 1 0
*
*/
public class IdentityMatrix {
public static void main(String[] args) {
int matrix[][] = {
{1,0,0,0},
{0,1,0,0},
{0,0,1,0},
{0,0,0,1}
};
/* int matrix[][] = {
{1,0,0},
{0,1,0},
{0,0,1}
};*/
int row = 4;
int column = 4;
//row and column should be same to make square matrix
if(row != column){
System.out.println("Given matrix is NOT a Identity Matrix");
return;
}
//main diagonal elements should be 1
for(int i=0;i<row;i++)
if(matrix[i][i] != 1){
System.out.println("Given matrix is NOT a Identity Matrix");
return;
}
//rest of the elements should be 0
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
if(i != j && matrix[i][j] != 0){
System.out.println("Given matrix is NOT a Identity Matrix");
return;
}
//if all the 3 conditions are satisfied
//Given matrix is Identity Matrix
System.out.println("Given matrix is a Identity Matrix");
}
}
/*
OUTPUT
matrix[][] = {
{1,0,0,0},
{0,1,0,0},
{0,0,1,0},
{0,0,0,1}
};
Given matrix is a Identity Matrix
OUTPUT
matrix[][] = {
{1,0,0},
{0,1,0},
{0,0,1},
};
Given matrix is a Identity Matrix
OUTPUT
matrix[][] = {
{1,1,1},
{0,1,1},
{1,0,1},
};
Given matrix is NOT a Identity Matrix
OUTPUT
matrix[][] = {
{1,0,0},
{0,1,0}
};
Given matrix is NOT a Identity Matrix
*/