Browse Source

String to matrix Method functional to parse 2by2 matrices

featureMatrixCalculator
Lukas Reichwein 5 years ago
parent
commit
c6b1fae7a6
  1. 27
      src/main/java/com/ugsbo/matrixcalc/MatrixCalcMath.java
  2. 41
      src/test/java/com/ugsbo/matrixcalc/StringToMatrixTest.java

27
src/main/java/com/ugsbo/matrixcalc/MatrixCalcMath.java

@ -1,5 +1,7 @@
package com.ugsbo.matrixcalc;
import java.util.ArrayList;
/**
* Contains all basic matrix math calculations.
*/
@ -226,4 +228,29 @@ public class MatrixCalcMath {
return false;
}
public double[][] stringToMatrix(String stringMatrix) {
ArrayList<String[]> singleNumbersArr = new ArrayList<String[]>();
//Splitting the strings into thier rows
String[] singleNumbers = null;
String[] rows = stringMatrix.split("\n");
for (int i = 0; i < rows.length; i++) {
System.out.println(rows[i]);
singleNumbers = rows[i].split("\\s");
singleNumbersArr.add(singleNumbers);
}
int rowCount = rows.length; //row.length
int columCount = singleNumbersArr.size(); //output.length
double[][] result = new double[columCount][rowCount];
for (int columIndex = 0; columIndex < singleNumbersArr.size(); columIndex++) {
for (int rowIndex = 0; rowIndex < singleNumbers.length; rowIndex++) {
result[columIndex][rowIndex] = Double.parseDouble(singleNumbersArr.get(columIndex)[rowIndex]);
}
}
return result;
}
}

41
src/test/java/com/ugsbo/matrixcalc/StringToMatrixTest.java

@ -0,0 +1,41 @@
package com.ugsbo.matrixcalc;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
/**
* Tests the funktionality to Calculate the Determinant of a Matrix.
*/
public class StringToMatrixTest {
private MatrixCalcMath matrixMath;
@Before
public void setup() {
matrixMath = new MatrixCalcMath();
}
@Test
public void StringWithSingleDigitNumbersToMatrix_ReturnsEquivalentMatrix() {
String inputString = "1";
double[][] expected = { { 1.0 } };
double[][] result = matrixMath.stringToMatrix(inputString);
assertArrayEquals("The first row is not correct", expected[0], result[0], 0.1);
}
@Test
public void StringWithfourDigitNumbersToMatrix_ReturnsEquivalentMatrix() {
String inputString = "1 2\n3 4";
double[][] expected = { { 1.0, 2.0 }, {3.0, 4.0} };
double[][] result = matrixMath.stringToMatrix(inputString);
assertArrayEquals("The first row is not correct", expected[0], result[0], 0.1);
assertArrayEquals("The first row is not correct", expected[1], result[1], 0.1);
}
}
Loading…
Cancel
Save