Java Matrix Multiply multiply(final double[][] A, final double[][] B)

Here you can find the source of multiply(final double[][] A, final double[][] B)

Description

multiply

License

Apache License

Parameter

Parameter Description
A a parameter
B a parameter

Declaration

public static final double[][] multiply(final double[][] A, final double[][] B) 

Method Source Code

//package com.java2s;
/**// ww w.ja v  a  2 s  . c  om
 * Copyright (C) 2012 Fredrik Ekelund <fredrik@ipx.se>
 *
 * This file is part of Decision Trees.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * 
     * @param A
     * @param B
     * @return
     */
    public static final double[][] multiply(final double[][] A, final double[][] B) {
        final int n = A.length;
        final int m = B.length;
        if (m == 0 || n == 0) {
            return new double[0][0];
        }

        final int p = B[0].length;
        if (m != A[0].length) {
            throw new IllegalArgumentException(
                    String.format("Non-conformant matrix dimensions: [%d x %d] * [%d x %d]", n, A[0].length, m, p));
        }

        if (p == 0) {
            return new double[0][0];
        }

        //      return uncheckedMultiply(A, B, n, m, p);
        return uncheckedMultiplyJAMA(A, B, n, m, p);
    }

    static double[][] uncheckedMultiplyJAMA(final double[][] A, final double[][] B, final int n, final int m,
            final int p) {
        final double[][] C = new double[n][p];
        final double[] bCol = new double[m];
        for (int j = 0; j < p; j++) {
            for (int k = 0; k < m; k++)
                bCol[k] = B[k][j];
            for (int i = 0; i < n; i++) {
                final double[] aRow = A[i];
                double sum = 0.0;
                for (int k = 0; k < m; k++) {
                    sum += aRow[k] * bCol[k];
                }

                C[i][j] = sum;
            }
        }

        return C;
    }
}

Related

  1. multiply(double[][] dest, double[][] a, double[][] b)
  2. multiply(double[][] m, double[] x)
  3. multiply(double[][] m1, double[][] m2)
  4. multiply(double[][] p, double[][] q)
  5. multiply(double[][] x, double[][] y)
  6. multiply(float[][] a, float num)
  7. multiply(float[][] a, float[][] b)
  8. multiply(int[][] mat1, int[][] mat2)
  9. multiply(String[] tempResult, int nextIndex, String[][] pys)