Question

I am trying to make multiplication of a mXn matrix and a mX1 vector in java. To do so, I am using a 2d arraylist for matrix and an ArrayList for the vector. My code is the following:

    ArrayList<Double> newList = new ArrayList<Double>();
    double sum = 0;

    for (int i = 0; i < eigenMatrix.size(); i++) {//eigenMatrix 2d ArrayList
        for (int j = 0; j < eigenMatrix.get(0).size(); j++) {

            sum +=  eigenMatrix.get(i).get(j)*imgMean.get(j); // imgMean an ArrayList
            System.out.println(sum+ " "+ i);
        }

        newList.add(sum); sum = 0;

    }
    System.out.println(newList);

I am having problems with sum variable. At the end I am having a mx1 output vector and every value its the same number. Am I doing something wrong? Or it could be data issue?

Était-ce utile?

La solution

hy, you are adding variable of primitive data type into newList. this is incorrect

double sum = 0; newList.add(sum); sum = 0;

you have declared a ArrayList of Double data type ArrayList newList = new ArrayList();

but you are adding newList.add(sum) where sum is a primitive data type of long.

Fix

you have to insert object of Double data type for each multiplication result.

newList.add(new Double(sum));

Autres conseils

The error is that you are referencing same variable sum in your array, so all elements of array pointed to the same result.

Quick fix:

add newList.add(new Double(sum)); instead of newList.add(sum);

and you'll create new Double for each result.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top