
C Sc 227 Lab: A Matrix Class
1. Add a constructor to make a copy of the 2D array of doubles passed as an argument.
2. Add three getters getNumRows(), getNumColumns(), and get(int)
3. Develop scalarMultiply(double scalar)inside Matrix with a 2D array instance variable.
4. Develop add(Matrix other)that modifies this Matrix, but not other
/**
* Create a new Eclipse project called Matrix
* Copy and paste this unit test into a file named MatrixTest
* Develop the 6 methods described above and expressed below in the test methods.
* First make the code compile, get a red bar, then get some assertions to pass.
*/
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class MatrixTest {
@Test
public void testGetters() {
double[][] a = { { 1.0, 2.0, 3.0 }, { 4.4, 5.5, 6.6 } };
// Create a new instance of Matrix with a copy of an allocated 2D array.
Matrix mat1 = new Matrix(a);
assertEquals(2, mat1.getNumRows());
assertEquals(3, mat1.getNumColumns());
double error = 1.0e-12;
assertEquals(1.0, mat1.get(0, 0), error);
assertEquals(2.0, mat1.get(0, 1), error);
assertEquals(3.0, mat1.get(0, 2), error);
assertEquals(4.4, mat1.get(1, 0), error);
assertEquals(5.5, mat1.get(1, 1), error);
assertEquals(6.6, mat1.get(1, 2), error);
// Ensure a change to a does not change the elements in the Matrix
a[0][0] = -999.9;
a[1][2] = -999.9;
assertEquals(1.0, mat1.get(0, 0), error);
assertEquals(6.6, mat1.get(1, 2), error);
}
@Test
public void testScalarMultiply() {
double[][] a = { { 1.0, 2.0, 3.0 }, { 4.4, 5.5, 6.6 } };
Matrix mat1 = new Matrix(a);
mat1.scalarMultiply(2.2);
double error = 1.0e-12;
// TODO: Complete this test method to assert all elements are 2.2 larger
assertEquals(2.2, mat1.get(0, 0), error);
}
@Test
public void testMatrixAddition() {
double[][] a = { { 1.0, 2.0, 3.0 }, { 4.4, 5.5, 6.6 } };
Matrix mat1 = new Matrix(a);
double[][] a2 = { { 1.11, 2.22, 3.33 }, { 124.678, -1.1, 0.0 } };
Matrix mat2 = new Matrix(a2);
mat1.add(mat2);
// TODO: Complete this test method to check all elements
double error = 1.0e-12;
assertEquals(2.11, mat1.get(0, 0), error);
}
}