How to add/subtract two arrays in java

8k views Asked by At

Anyone know how to convert those python program to java? i have no idea how to add/subtract two array and normalizing array in java, or i need using matrix?

P1 = array([xA, yA, zA])
P2 = array([xB, yB, zB])
P3 = array([xC, yC, zC])

ex = (P2 - P1)/(numpy.linalg.norm(P2 - P1))
i = dot(ex, P3 - P1)
ey = (P3 - P1 - i*ex)/(numpy.linalg.norm(P3 - P1 - i*ex))
ez = numpy.cross(ex,ey)
d = numpy.linalg.norm(P2 - P1)
j = dot(ey, P3 - P1)

triPt = P1 + x*ex + y*ey + z*ez
2

There are 2 answers

3
jev On BEST ANSWER

If you use plain arrays, you would need to loop through the elements. Consider using a Matrix package, e.g. http://math.nist.gov/javanumerics/jama/.

Something like (assuming a is a 2d-array):

import Jama.*

Matrix A = new Matrix(a);
Matrix B = new Matrix(b);
Matrix R = A.minus(B);
0
iluvthee07 On

Setting up a loop would be the simplest method for adding two arrays or matrices:

//For two arrays a[n] and b[n], finding array c[n] such that c = a - b;

for (int i=0; i<n; i++)
   c[i] = a[i] - b[i];

//For matrices A & B of order m X n when expressed as 2d arrays:

for (int i=0; i<n; i++)
   for(int j=0; j<m; j++)
      c[i][j] = a[i][j] + b[i][j];

For a Matrix that is used as a object, you may define functions to work on the above lines.

Hope this helps!