class returns a null, giving nullpointerexception

hi

i've been trying to create math class to do matrix math. but the class returns a null instead of matrix. if i put the function outside the class it works fine.

int input = 2, node = 6, output = 2;
float[][] inputs= new float[input][1], nodes = new float[node][1], outputs = new float[output][1], nodeBias = new 
float[node][1], outputBias = new float[output][1];
float[][] inputsToNode = new float[node][input], nodeToOutput = new float[output][node];

Math m;

void setup() {
  size(100, 100);

  println(inputsToNode[5][1]);
  inputsToNode = m.weightFill(inputsToNode, node, input);
  println(inputsToNode[5][1]);
}

class Math {

  float[][] weightFill(float[][] k, int Height, int Width) {
    for (int i=0; i<Height; i++) {
      for (int j=0; j<Width; j++) {
        k[i][j] = random(-1, 1);
      }
    }
    return k;
  }
}

thanks

Tagged:

Answers

  • where do you instantiate m?

  • Answer ✓
    • Java is already bundled w/ classes Math & StrictMath. ~O)
    • So you're better off naming your custom class w/ something else. :-\"
    • Your method weightFill() only deals w/ parameter variables passed to it. L-)
    • Therefore, it's advisable to declare it static. *-:)
    • However, if you do so, your class itself needs to be declared static as well. 8-|
    • Unless you place your class in a separate ".java" file tab. :-bd
  • so i changed my math class >> to static class matrixMath {} but i use the random function and static does not love the random function :P gives me this: cannot make a static reference to the non static method random.

    other suggestions? :)

  • edited February 2018

    You can use Java's Math.random() in place of Processing's random(): *-:)
    https://Docs.Oracle.com/javase/9/docs/api/java/lang/Math.html#random--

    But given the former returns a double value, you may need to downcast it w/ (float). :ar!

  • for your original problem, rename your Math class, something better then Math2. and instantiate m using:

    Math2 m = new Math2();
    

    then the original code won't give you an npe.

    but, yes, as it is your class is pointless.

  • so maybe i should write the function in a new tab but before i create the matrixMath class?

  • There's loads of (java) libraries out there for doing Matrix math, why not just use one of them?

Sign In or Register to comment.