In: Computer Science
package applications;
public class Matrix
{
private int[][] m;
public Matrix(int x, int y)
{
m = new int[x][y];
}
public Matrix(int x, int y, int z)
{
m = new int[x][y];
for(int i = 0; i < x; i++)
{
for(int j = 0; j < y; j++)
{
m[i][j] = z;
}
}
}
public int rowsum(int i) throws IndexOutOfBoundsException
{
if (i < 0 || i > m.length-1)
{
throw new IndexOutOfBoundsException("Invalid Row");
}
int sum = 0;
for(int j = 0; j < m[i].length; j++)
{
sum += m[i][j];
}
return sum;
}
public static void main(String[] args)
{
Matrix A = new Matrix(100, 100, 1);
System.out.println(A.rowsum(99));
System.out.println("Done!");
Matrix B = new Matrix(1000, 1000, 1);
System.out.println("Done!");
Matrix C = new Matrix(10000, 10000, 1);
System.out.println("Done!");
}
}
1)add method columnSum(j)
2)add method max() which returns the largest value that contain in the matrix
3)add method trace() i.e., if matrix is not square, then throw error otherwise compute the sum of the entries on the diagnol.
package applications; public class Matrix { private int[][] m; public Matrix(int x, int y) { m = new int[x][y]; } public Matrix(int x, int y, int z) { m = new int[x][y]; for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { m[i][j] = z; } } } public int rowsum(int i) throws IndexOutOfBoundsException { if (i < 0 || i > m.length - 1) { throw new IndexOutOfBoundsException("Invalid Row"); } int sum = 0; for (int j = 0; j < m[i].length; j++) { sum += m[i][j]; } return sum; } public int colsum(int i) throws IndexOutOfBoundsException { if (i < 0) { throw new IndexOutOfBoundsException("Invalid Row"); } int sum = 0; for (int j = 0; j < m.length; j++) { if (i > m[j].length - 1) { throw new IndexOutOfBoundsException("Invalid Row"); } sum += m[j][i]; } return sum; } public int max() { int maxValue = m[0][0]; for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[i].length; j++){ if (m[i][j] > maxValue) { maxValue = m[i][j]; } } } return maxValue; } public int trace() { int sum = 0; for (int i = 0; i < m.length; i++) { if (m[i].length != m.length) { throw new IllegalStateException("Matrix is not square"); } sum += m[i][i]; } return sum; } public static void main(String[] args) { Matrix A = new Matrix(100, 100, 1); System.out.println(A.rowsum(99)); System.out.println("Done!"); System.out.println(A.colsum(10)); System.out.println("Done!"); System.out.println("Max: " + A.max()); System.out.println("Done!"); System.out.println("Trace: " + A.trace()); System.out.println("Done!"); Matrix B = new Matrix(1000, 1000, 1); System.out.println("Done!"); Matrix C = new Matrix(10000, 10000, 1); System.out.println("Done!"); } }