You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
*A matrix is sparse if many of its coefficients are zero (In general if 2/3rd of matrix elements are 0, it is considered as sparse).
5
+
*The interest in sparsity arises because its exploitation can lead to enormous computational savings and because many large matrix problems that occur in practice are sparse.
6
+
*
7
+
* @author Ojasva Jain
8
+
*/
9
+
10
+
classSparcity{
11
+
/*
12
+
* @return Sparcity of matrix
13
+
*
14
+
* where sparcity = number of zeroes/total elements in matrix
15
+
*
16
+
*/
17
+
staticdoublesparcity(double [][] mat){
18
+
intzero =0;
19
+
//Traversing the matrix to count number of zeroes
20
+
for(inti=0;i<mat.length;i++){
21
+
for(intj=0;j<mat[i].length;j++){
22
+
if(mat[i][j]==0)
23
+
zero++;
24
+
}
25
+
}
26
+
//return sparcity
27
+
return ((double)zero/(mat.length*mat[1].length));
28
+
}
29
+
30
+
//Driver method
31
+
publicstaticvoidmain(String [] args){
32
+
Scannerin = newScanner(System.in);
33
+
System.out.println("Enter number of rows in matrix: ");
34
+
intn = in.nextInt();
35
+
System.out.println("Enter number of Columns in matrix: ");
36
+
intm = in.nextInt();
37
+
38
+
System.out.println("Enter Matrix elements: ");
39
+
double [][] mat = newdouble[n][m];
40
+
for(inti=0;i<n;i++){
41
+
for(intj=0;j<m;j++){
42
+
mat[i][j] = in.nextDouble();
43
+
}
44
+
}
45
+
System.out.println("Sparcity of matrix is: "+ sparcity(mat));
0 commit comments