File MatrixSmallestjava shown above contains an incomplete p
File MatrixSmallest.java (shown above) contains an incomplete program. The goal of the program is to compute the position-wise minima of two matrices (a matrix is a two-dimensional array). Complete that program, by defining a matrixSmallest function, that satisfies the following specs:
Function matrixSmallest takes two arguments, called A, B. They are both 2D arrays of double numbers.
If the two arrays do NOT have the same size (i.e., equal rows, and equal columns), the function should return null.
Otherwise, the function should return a 2D array called result, with rows and columns equal to those of A, such that the value at position (i, j) of the result is the smallest between the value at position (i, j) of A and the value at position (i, j) of B.
IMPORTANT: You are NOT allowed to modify in any way the main function. You are free to define and use auxiliary functions.
The complete program should produce this output:
Solution
public class MatrixSmallest
{
public static void printDoubleMatrix(String name, double[][] a)
{
if (a == null)
{
System.out.printf(\"%s: null\ \", name);
return;
}
System.out.printf(\"%s:\ \", name);
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
System.out.printf(\"%7.1f\", a[i][j]);
}
System.out.printf(\"\ \");
}
System.out.printf(\"\ \");
}
//matrixSmallest method. This returns a 2D array of doubles
public static double[][] matrixSmallest(double a[][], double b[][]){
//checking if dimensions are mismatched
if(a.length!=b.length && a[0].length!=b[0].length){
return null;
}
else{
//declaring matrix to store matrixsmallest
double matrixsmallest[][] = new double[a.length][a[0].length];
//iterating through the matrices to find the minimum
for (int i=0; i<a.length; i++){
for(int j=0; j<a[0].length; j++){
if(a[i][j]<=b[i][j]){
//minimum value in matrixsmallest
matrixsmallest[i][j] = a[i][j];
}
else{
//minimum value in matrixsmallest
matrixsmallest[i][j] = b[i][j];
}
}
}
//return statement
return matrixsmallest;
}
}
public static void main(String[] args)
{
double[][] a = { {3.2, 2.1, 5.3},
{8.0, 4.9, 5.7} };
double[][] b = { {1.1, 2.2, 3.3},
{4.4, 5.5, 6.6} };
double[][] result = matrixSmallest(a, b);
printDoubleMatrix(\"a\", a);
printDoubleMatrix(\"b\", b);
printDoubleMatrix(\"result\", result);
}
}

