If you want to add matrices, you can use loops in Java, but also streams. This is a sample implementation of matrix addition using streams:
public class MatrixOperations {
public static double[][] add(double[][] a, double[][] b) {
return range(0, a.length).boxed().collect(
() -> new double[a.length][a[0].length], // create the accumulator matrix which is to be returned
(acc, row) -> range(0, a[row].length).forEach(col -> acc[row][col] = a[row][col] + b[row][col]), // sum each value
(acc, r) -> {}); // ignore
}
// Test method
public static void main(String[] args) {
double[][] a = {{1.0, 3.0}, {1.0, 0.0}, {1.0, 2.0}};
double[][] b = {{.0, .0}, {7.0, 5.0}, {2.0, 1.0}};
double[][] sum = add(a, b);
Stream.of(sum).map(Arrays::toString).forEach(System.out::println);
}
}
If you run this class you will get the following output:
[1.0, 3.0]
[8.0, 5.0]
[3.0, 3.0]
i == values.length->i < values.length. same forjm.valuesandvalueshave the same dimensions? Do the number of rows equal the number of columns? You are assuming these things.for (int i = 0; i < values.length; i++) { for (int j = 0; j < values[i].length; j++) {