Ben
Ben

Reputation: 141

multiply a 2d array by a 1d array

I've initialized a 1d and 2d array and now I basically just want to be able to perform matrix multiplication on them. However, I'm not quite getting the proper answer. I think I've mixed up the for loop where I try to ensure I only multiply the correct values, but can't quite get the hang of it.

edit: I've fixed it, I was misunderstanding what the length method of a 2D array returned (thought it returned columns and not rows). The below code is my corrected code. Thanks everyone.

public static double[] getOutputArray(double[] array1D, double[][] array2D) {
    int oneDLength = array1D.length;
    int twoDLength = array2D[0].length;
    double[] newArray = new double[array2D[0].length]; // create the array that will contain the result of the array multiplication  
    for (int i = 0; i < twoDLength; i++) { // use nested loops to multiply the two arrays together
        double c = 0;
        for (int j = 0; j < oneDLength; j++) {
            double l = array1D[j];
            double m = array2D[j][i];
            c += l * m; // sum the products of each set of elements
        }
        newArray[i] = c;
    }
    return newArray; // pass newArray to the main method
} // end of getOutputArray method

Upvotes: 0

Views: 2542

Answers (1)

G&#225;bor Bakos
G&#225;bor Bakos

Reputation: 9100

There are some problems, first of all, you should decide how the vectors represented, are you multiplying from left or right.

For the maths: vector 1xn times matrix nxm will result in 1xm, while matrix mxn times nx1 result in mx1.

I think the following would work for you:

public static double[] getOutputArray(double[] array1D, double[][] array2D) {
  int oneDLength = array1D.length;
  int twoDLength = array2D.length;
  double[] newArray = new double[twoDLength]; // create the array that will contain the result of the array multiplication
  assert twoDLength >0 && array2D[0].length == oneDLength;
  for (int i = 0; i < twoDLength; i++) { // use nested loops to multiply the two arrays together
      double c = 0;
      for (int j = 0; j < oneDLength; j++) {
          double l = array1D[j];
          double m = array2D[i][j];
          c += l * m; // sum the products of each set of elements
      }
      newArray[i] = c;
   }
   return newArray; // pass newArray to the main method
} // end of getOutputArray method

I hope I did not make a mistake, while trying to fix.

Upvotes: 1

Related Questions