0

I have an object calld Matice. Matice is a matrix nxn filled with random numbers in a set range. I want to perform some operations on my objects like adding, multiplying, inversion, etc. How can i do that? If i try something like m1[i][j] * m2[j][i]. but i get error message.

    public class Main {
    public static void main(String[] args) {
        Matice m1 = new Matice(3);
        m1.matrixFill(0, 5);
        m1.matrixPrint();
        //m1.matrixAdd(m2);
    }
}



public class Matice {

int[][] matice;
private int n;

public Matice(int n) {
    this.n = n;
    if(n > 0) {
        matice = new int[n][n];
    }
}

public void matrixPrint(){
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            System.out.format("%5d", matice[i][j]);                
        }
        System.out.println("");
    }
    System.out.println("");
}

public void matrixFill(int a, int b){
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            matice[i][j] = (int) (Math.random() * (a + b + 1) - a);                
        }
    }
}

public void matrixAdd(Matice m1, Matice m2){
    int[][] resultMatrix = new int[n][n];        
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            resultMatrix[i][j] = m1[i][j] + m2[i][j];
        }            
    }
}    
}
stryke404
  • 27
  • 7

2 Answers2

0

You are referring to the object itself not the array that is the field of object.

Try this:

resultMatrix[i][j] = m1.matice[i][j] + m2.matice[i][j];

instead of

resultMatrix[i][j] = m1[i][j] + m2[i][j];

btw. I recommend to mark matrixAdd to static because it is a stateless, helper method or extract into a different class.

Lexandro
  • 765
  • 5
  • 14
0

You already started the right way: by adding the operations as methods to your Matice class. Unlike C++, you can not define operators for your class. You'll have to stick with ordinary methods.

Your methods should use the Matice they are called on as one argument. Thus use something like add(Matice other) Next you'll have to decide if you methods modify the Matice they are called on, or if they return a copy of the data.

Last but not least, if this isn't a toy/exercise project, I'd check out existing libraries: Java matrix libraries

Community
  • 1
  • 1
ruediste
  • 2,434
  • 1
  • 21
  • 30
  • Yes this is just an exersise project for my college exam. Thank's for the comment. I wrote the program like you suggested and it works great! – stryke404 May 18 '14 at 19:29