Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package module5;
- import java.lang.reflect.Array;
- import java.util.Arrays;
- public class Matrix {
- // Instance variable to store matrix contents
- private double[][] contents;
- // Constructor
- public Matrix(double[][] m){
- this.contents = m; // Set the contents variable to constructor's argument
- }
- // Number of rows - Non static
- public int nRows(){
- return this.contents.length;
- }
- // Number of columns (in first row) - Non static
- public int nCols(){
- return this.contents[0].length;
- }
- // Is current matrix square? - Non static
- public boolean isSquare(){
- if(nRows() == nCols()){
- return true;
- } else {
- return false;
- }
- }
- // Create a new matrix containing diagonal elements of original - Non static
- public Matrix diagonal() throws Exception{
- // Determine if matrix is square or not
- if (!this.isSquare()){
- throw new Exception("Matrix is not square");
- } else {
- // Create a new array to store the diagonal values
- double[][] a1 = new double[nCols()][nRows()];
- for(int i = 0; i < nCols(); i++){
- // Step through the diagonal elements only
- a1[i][i] = this.contents[i][i];
- }
- System.out.println(Arrays.deepToString(a1)); // Seems to work
- return new Matrix(a1); // How would i print this? System.out.println(Matrix(a1))???
- }
- }
- // Add two matrices - Non static
- public Matrix add(Matrix m2) throws Exception {
- if(this.nCols() != m2.nCols()){
- throw new Exception("Number of coloumns do not match");
- } else if(this.nRows() != m2.nRows()) {
- throw new Exception("Number of rows do not match");
- } else {
- // Create a new array to store the addition
- double[][] m3 = new double[nCols()][nRows()];
- // Cycle over each row
- for(int x = 0; x < nRows(); x++){
- // Within each row, cycle over each column
- for(int y = 0; y < nCols(); y++){
- m3[x][y] = this.contents[x][y] + m2[x][y]; // m2 - The type of the expression must be an array type but it resolved to Matrix
- }
- }
- System.out.println(Arrays.deepToString(m3));
- return new Matrix(m3);
- }
- }
- public static void main(String[] args) throws Exception {
- // Define the contents of an array
- double[][] contents = {
- {1.0,2.1,3.2,4.3},
- {11.5,12.6,13.7,14.8},
- {11.9,12.0,13.1,14.2},
- {11.9,12.0,13.1,14.2}
- };
- // Create a new Matrix object with contents
- Matrix m1 = new Matrix(contents);
- //System.out.println(m1.nRows());
- //System.out.println(m1.nCols());
- //System.out.println(m1.isSquare());
- System.out.println(m1.diagonal());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement