Timo Güntner
Timo Güntner

Reputation: 2861

Adding a Matrix and an Array

I'm currently trying to add a Matrix with an Array.

This is the code I have right now:

public void add(Matrix m) {

    for(int i = 0; i == values.length; i++) {
        for(int j = 0; j == values.length; j++) {
            m.values[i][j] = m.values[i][j] + values[i][j];
        }
    }

}

I would appreciate any help I can get, thanks!

Upvotes: 1

Views: 603

Answers (3)

gil.fernandes
gil.fernandes

Reputation: 14641

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]

Upvotes: 1

augarte
augarte

Reputation: 57

Check for the dimensions of the Array and the Matrix to be the same.

public void add(Matrix m) {
    for(int i = 0; i < values.length; i++) {
        for(int j = 0; j < values[i].length; j++) {
            m.values[i][j] = m.values[i][j] + values[i][j];
        }
    }
}

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

In Java language there are no word of matrix or 2D or nD array there are an array of array.

About your problem try this :

for (int i = 0; i < values.length; i++) {
    for (int j = 0; j < values[i].length; j++) {
  • The first loop for (int i = 0; i < values.length; i++) { return array by array { 2, 4, 5 } and { 3, 7, 2 } and { -2, 0, 1 } and { 5, 1, 1 }
  • The second loop for (int j = 0; j < values[i].length; j++) { return value by values of each array from the first loop if we took the first array it will return 2 and 4 and 5

Upvotes: 2

Related Questions