Java // Array // Multiplication // For-loop;

213 Views Asked by At

Objective: Produce rotation using the rotation matrix;

private double[][] rotateX = {{1.00,0.00,0.00},{0.00,Math.cos(theta),Math.sin(-theta)},{0.00,Math.sin(theta),Math.cos(theta)}};   // Rotation matrice for x axis;

Problem definition: Output does not match the expectation;

Expected output:

newX = 3
newY = -2.236 
newZ = -0.002
// Checked in MathCAD;

Output produced:

newX = 3.00
newY =-2.00
newZ = 1.0000000000000002

Code applied:

public class Test2 {
private double[] target = {3.00,1.00,2.00};        // target data for matrix multiplication;
private double[] product = {0.00,0.00,0.00};       // product of the for-loop;

private double theta = Math.toRadians(90.00);      // Rotation angle;

private double[][] rotateX = {{1.00,0.00,0.00},
        {0.00,Math.cos(theta),Math.sin(-theta)},
        {0.00,Math.sin(theta),Math.cos(theta)}};   // Rotation matrice for x axis;

private void rotateAroundX(){
    double temp;                                  // temp. data storage;

    double newX = 0.00;                           // new x after for-loop;
    double newY = 0.00;                           // new y after for-loop;
    double newZ = 0.00;                           // new z after for-loop;

    for(int i = 0; i < rotateX.length ; i ++){          // check how many items are stored in the matrix;
        for(int j = 0; j < rotateX[i].length; j++){     // check how many elements are stored in each item;

            temp = rotateX[i][j] * target[j];           // store product of the multiplication in temp;

            if(i == 0){
                newX += temp;                           // if i index is 0 finalize matrix multiplication and set newX; Ex. 1 row of rotateX - (1.00*3.00 + 0.00*1.00 + 0.00*2.00); 
            }
            if(i == 1){                                 // if i index is 1 finalize matrix multiplication and set newY;
                newY += temp;
            }
            if(i == 2){                                 // if i index is 2 finalize matrix multiplication and set newZ;
                newZ += temp;
            }
        }
    }

    this.product[0] = newX;                             // Add newX to product;
    this.product[1] = newY;                             // Add newY to product;
    this.product[2] = newZ;                             // Add newZ to product;                 

}

public void sart(){
    rotateAroundX();                   // run test-case;

    for (double e : product){
        System.out.println(e);         // output the product information;
    }
}
}
2

There are 2 best solutions below

0
On

I think the answer is a bit strange, but simple: your expected output is wrong. To me your produced output seems right.

3
On

You are using radians whereas in your expected output you are using degrees.

Changing

private double theta = Math.toRadians(90.00);

to:

private double theta = 90;

gives you expected output.