Question

Using java fix the code I implemented so that it passes the JUnit Tests. MATRIX3 public...

Using java fix the code I implemented so that it passes the JUnit Tests.

MATRIX3

public class Matrix3 {

private double[][] matrix;

/**

* Creates a 3x3 matrix from an 2D array

* @param v array containing 3 components of the desired vector

*/

public Matrix3(double[][] array) {

this.matrix = array;

}

/**

* Clones an existing matrix

* @param old an existing Matrix3 object

*/

public Matrix3(Matrix3 old) {

matrix = new double[old.matrix.length][];

for(int i = 0; i < matrix.length; i++) {

matrix[i] = new double[old.matrix[i].length];

for(int j = 0; j < matrix[i].length; j++) {

matrix[i][j] = old.matrix[i][j];

}

}

}

/**

* Returns a matrix element at a row, column

* @param row row

* @param column column

* @return matrix element as a scalar

*/

public double getElement (int row, int column){

return matrix[row][column];

}

/**

* Returns matrix elements as a 2D array

* @return 2D array containing matrix elements

*/

public double[][] getElements (){

return matrix;

}

VECTOR3

public class Vector3 implements Comparable <Vector3>{

private final double x;

private final double y;

private final double z;

/**

* Creates a 3D vector from an array

* @param v array containing 3 components of the desired vector

*/

public Vector3(double[] v) {

this(v[0], v[1], v[2]);

}

/**

* Creates a 3D vector from 3 numeric scalar components

* @param x x coordinate

* @param y y coordinate

* @param z z coordinate

*/

public Vector3(double x, double y, double z) {

this.x = x;

this.y = y;

this.z = z;

}

/**

* Clones an existing vector

* @param old an existing Vector3 object

*/

public Vector3(Vector3 old) {

this(old.x, old.y, old.z);

}

/**

* Returns a vector component at a specified index

* @param index the index of the vector component

* @return vector component as a scalar

*/

public double getElement (int index){

return new double[] {x, y, z}[index];

}

/**

* Returns vector components as an array

* @return

*/

public double[] getElements (){

return new double[] {x, y, z};

}

MVMATH

public class MVMath {

/**

* Multiplies a matrix by a vector

* @param m matrix

* @param v vector

* @return new matrix object containing the result

*/

public static Vector3 multiply (Matrix3 m, Vector3 v){

}

/**

* @param m1 matrix 1

* @param m2 matrix 2

* @return new matrix object containing the result

*/

public static Matrix3 multiply(Matrix3 m1, Matrix3 m2) {

double arr[][] = new double[3][3];

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

double sum = 0;

for (int k = 0; k < 3; k++)

sum += m1.getElement(i, k) * m2.getElement(k, j);

arr[i][j] = sum;

}

}

return new Matrix3(arr);

}

/**

* Computes a cross product of two vectors

* @param v1 vector 1

* @param v2 vector 2

* @return a new vector object containing the result

*/

public static Vector3 crossProduct (Vector3 v1, Vector3 v2){

double x, y, z;

x = v1.getElement(1) * v2.getElement(2) - v1.getElement(2) * v2.getElement(1);

y = v1.getElement(2) * v2.getElement(0) - v1.getElement(0) * v2.getElement(2);

z = v1.getElement(0) * v2.getElement(1) - v1.getElement(1) * v2.getElement(0);

return new Vector3(x, y, z);

}

/**

* Computes a dot product of two vectors

* @param v1 vector 1

* @param v2 vector 2

* @return dot product (a scalar)

*/

public static double dotProduct (Vector3 v1, Vector3 v2){

return v1.getElement(0)*v2.getElement(0)+v1.getElement(1)*v2.getElement(1)+v1.getElement(2)*v2.getElement(2);

}

}

JUnit:

public class MVMathTest {

@Test

public void testMatrixMult() {

double[][] one = {{1d, 2d, 3d},

{4d, 5d, 6d},

{7d, 8d, 9d}};

double[][] two = {{11d, 12d},

{21d, 22d},

{31d, 32d}};

double[][] expected = {{146d, 152d},

{335d, 350d},

{524d, 548d}};

Matrix3 m1= new Matrix3 (one);

Matrix3 m2= new Matrix3 (two);

double [][] result = MVMath.multiply(m1, m2).getElements();

String error = String.format("Matrix multiplication failed ");

for (int i = 0; i < expected.length; i++){

for (int j = 0; j < expected[0].length; j++){

assertEquals(error, result[i][j], expected[i][j], 1e-6);

}

}

}

@Test

public void testMatrixMult2() {

double[][] one = {{1d, 2d, 3d},

{4d, 5d, 6d}};

Matrix3 m1= new Matrix3 (one);

try {

MVMath.multiply(m1, m1);

String error = String.format("MVMath.multiply() failed to throw an exception");

fail(error);

} catch (IllegalArgumentException x) {

// ok

} catch (Exception x) {

fail("wrong type of exception thrown");

}

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Please note that I have completed the code for passing the given JUnit tests only (for the multiply method), if there are more tests that I’m not aware of, I can’t help with that. I have also completed multiply method taking Matrix3 and Vector3 objects. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

Note: Your Vector3 class need to implement compareTo method to compile correctly. If you do not want that, please remove ‘implements Comparable<Vector3>’ from Vector3 class header before compiling.

// MVMath.java

public class MVMath {

      /**

      *

      * Multiplies a matrix by a vector

      *

      * @param m

      *            matrix

      *

      * @param v

      *            vector

      *

      * @return new matrix object containing the result

      */

      public static Vector3 multiply(Matrix3 m, Vector3 v) {

            if (m.getElements()[0].length != v.getElements().length) {

                  // number of columns in m must be equal to number of elements in v,

                  // otherwise we can't perform multiplication

                  throw new IllegalArgumentException();

            }

            double arr[] = new double[v.getElements().length];

            for (int i = 0; i < arr.length; i++) {

                  double sum = 0;

                  // multiplying every j'th element in row i in matrix with j'th

                  // element in vector, summing values

                  for (int j = 0; j < m.getElements()[0].length; j++) {

                        sum += m.getElement(i, j) * v.getElement(j);

                  }

                  //storing sum in arr[i]

                  arr[i] = sum;

            }

            return new Vector3(arr);

      }

      /**

      *

      * @param m1

      *            matrix 1

      *

      * @param m2

      *            matrix 2

      *

      * @return new matrix object containing the result

      */

      public static Matrix3 multiply(Matrix3 m1, Matrix3 m2) {

            // finding rows and columns in m1

            int row1 = m1.getElements().length;

            int col1 = m1.getElements()[0].length;

            // finding rows and columns in m2

            int row2 = m2.getElements().length;

            int col2 = m2.getElements()[0].length;

            // if num columns in first matrix is not equal to num rows in second,

            // matrices cant be multiplied.

            if (col1 != row2) {

                  // throwing exception

                  throw new IllegalArgumentException();

            }

            double arr[][] = new double[row1][col2];

            for (int i = 0; i < row1; i++) {

                  for (int j = 0; j < col2; j++) {

                        double sum = 0;

                        for (int k = 0; k < col1; k++)

                              sum += m1.getElement(i, k) * m2.getElement(k, j);

                        arr[i][j] = sum;

                  }

            }

            return new Matrix3(arr);

      }

      /**

      *

      * Computes a cross product of two vectors

      *

      * @param v1

      *            vector 1

      *

      * @param v2

      *            vector 2

      *

      * @return a new vector object containing the result

      */

      public static Vector3 crossProduct(Vector3 v1, Vector3 v2) {

            double x, y, z;

            x = v1.getElement(1) * v2.getElement(2) - v1.getElement(2)

                        * v2.getElement(1);

            y = v1.getElement(2) * v2.getElement(0) - v1.getElement(0)

                        * v2.getElement(2);

            z = v1.getElement(0) * v2.getElement(1) - v1.getElement(1)

                        * v2.getElement(0);

            return new Vector3(x, y, z);

      }

      /**

      *

      * Computes a dot product of two vectors

      *

      * @param v1

      *            vector 1

      *

      * @param v2

      *            vector 2

      *

      * @return dot product (a scalar)

      */

      public static double dotProduct(Vector3 v1, Vector3 v2) {

            return v1.getElement(0) * v2.getElement(0) + v1.getElement(1)

                        * v2.getElement(1) + v1.getElement(2) * v2.getElement(2);

      }

}

Add a comment
Know the answer?
Add Answer to:
Using java fix the code I implemented so that it passes the JUnit Tests. MATRIX3 public...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java Here is the template public class ShiftNumbers { public static void main(String[] args) { // TODO:...

    Java Here is the template public class ShiftNumbers { public static void main(String[] args) { // TODO: Declare matrix shell size // TODO: Create first row // TODO: Generate remaining rows // TODO: Display matrix } /** * firstRow * * This will generate the first row of the matrix, given the size n. The * elements of this row will be the values from 1 to n * * @param size int Desired size of the array * @return...

  • hey I need help finishing this simplex program. public class Main {       /**       *...

    hey I need help finishing this simplex program. public class Main {       /**       * @param args       */       public static void main(String[] args) {             // TODO Auto-generated method stub             //FAIRE LES TODO dans Simplex             test1();test2();                   }       private static void test1() {             double[][] A = {                         { -1, 1, 0 },                         { 1, 4, 0 },                         { 2, 1, 0 },                         { 3, -4, 0 },                        ...

  • This is my code that i need to finish. In BoxRegion.java I have no idea how...

    This is my code that i need to finish. In BoxRegion.java I have no idea how to create the constructor. I tried to use super(x,y) but It is hard to apply. And Also In BoxRegionHashTable, I don't know how to create displayAnnotation BoxRegion.java ------------------------------------------------ public final class BoxRegion { final Point2D p1; final Point2D p2; /** * Create a new 3D point with given x, y and z values * * @param x1, y1 are the x,y coordinates for point...

  • /** * A collection of methods related to multi-dimensional arrays. */ public class Array2Lab { /**...

    /** * A collection of methods related to multi-dimensional arrays. */ public class Array2Lab { /** * Return whether k is in list. * Precondition: the elements of list are not null. * @param list the array to be searched. * @param k the number to search for. * @return true if k is an element of list, and false otherwise. */ public static boolean contains(Object[][] list, Object k) { return false; }    /** * Create a String that...

  • I am currently using eclipse to write in java. A snapshot of the output would be...

    I am currently using eclipse to write in java. A snapshot of the output would be greatly appreciated to verify that the program is indeed working. Thanks in advance for both your time and effort. Here is the previous exercise code: /////////////////////////////////////////////////////Main /******************************************* * Week 5 lab - exercise 1 and exercise 2: * * ArrayList class with search algorithms * ********************************************/ import java.util.*; /** * Class to test sequential search, sorted search, and binary search algorithms * implemented in...

  • In java---- The DeckTester.java file, provides a basic set of Deck tests. Add additional code at...

    In java---- The DeckTester.java file, provides a basic set of Deck tests. Add additional code at the bottom of the main method to create a standard deck of 52 cards and test the shuffle method ONLY in the Deck class. After testing the shuffle method, use the Deck toString method to “see” the cards after every shuffle. Deck: import java.util.List; import java.util.ArrayList; /** * The Deck class represents a shuffled deck of cards. * It provides several operations including *...

  • cant understand why my toString method wont work... public class Matrix { private int[][] matrix; /**...

    cant understand why my toString method wont work... public class Matrix { private int[][] matrix; /** * default constructor -- * Creates an matrix that has 2 rows and 2 columns */ public Matrix(int [][] m) { boolean valid = true; for(int r = 1; r < m.length && valid; r++) { if(m[r].length != m[0].length) valid = false; } if(valid) matrix = m; else matrix = null; } public String toString() { String output = "[ "; for (int i...

  • Question 1: Fix the 2D dynamic array initialization in following code #include <iostream> using namespace std;...

    Question 1: Fix the 2D dynamic array initialization in following code #include <iostream> using namespace std; int main(){    int rows = 5; int cols = 5; int x;    int** arr = new int[rows][cols]    cin >> x; arr[x][x] = x; cout << "arr[x][x] = " << arr[x][x];    return 0; } Question 2: Fix the code to initialize the 2D array elements to x #include <iostream> using namespace std; int main(){    int rows; int cols; int x;...

  • Q21 Read the following code: 8 Points public class Main { public static int[][] doStuff() {...

    Q21 Read the following code: 8 Points public class Main { public static int[][] doStuff() { int[][] array2D = new int[3][2]; for (int i = 0; i < array2D.length; i++) { for (int j = 0; j < array2D[0].length; j++) { array2D[i][j] = (i+j)%2; } } return array2D; فه public static void main(String[] args) { int[][] a = doStuff(); مہ سره Q21.1 What are the contents of array a? 6 Points Write your answer as if printing the elements row-by-row....

  • java : here is a code that I have to implement. counting the occuence in an...

    java : here is a code that I have to implement. counting the occuence in an array /** * _Part 3: Implement this method._ * * Counts the items in the ordered array list that are equal to the item at * the specified index. Be sure to take advantage of the fact that the list * is sorted here. You should not have to run through the entire list to * make this count. * * @param index an...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT