Here you can find the source of matrixProduct(double[][] A, double[][] B)
Parameter | Description |
---|---|
A | mxn matrix |
B | nxq matrix |
public static double[][] matrixProduct(double[][] A, double[][] B) throws Exception
//package com.java2s; /*//w ww.j a v a2 s .co m * Java Information Dynamics Toolkit (JIDT) * Copyright (C) 2012, Joseph T. Lizier * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ public class Main { /** * Return the matrix product A x B * * @param A mxn matrix * @param B nxq matrix * @return mxq matrix product of A and B */ public static double[][] matrixProduct(double[][] A, double[][] B) throws Exception { if (A[0].length != B.length) { throw new Exception("Number of columns of a " + A[0].length + " does not match the number of rows of b " + B.length); } double[][] result = new double[A.length][B[0].length]; for (int r = 0; r < result.length; r++) { for (int c = 0; c < result[r].length; c++) { result[r][c] = 0; for (int k = 0; k < A[r].length; k++) { result[r][c] += A[r][k] * B[k][c]; } } } return result; } /** * Return the matrix product v A * (i.e. a left multiplication of the 1xn vector and the nxm matrix A) * * @param v a 1xn vector * @param A an nxm matrix * @return a 1xm vector output */ public static double[] matrixProduct(double[] v, double[][] A) throws Exception { if (v.length != A.length) { throw new Exception( "Number of entries of v " + v.length + " does not match the number of rows of A " + A.length); } // Result length is the number of columns of A double[] result = new double[A[0].length]; for (int c = 0; c < result.length; c++) { result[c] = 0; for (int r = 0; r < v.length; r++) { result[c] += v[r] * A[r][c]; } } return result; } /** * Return the matrix product A v * (i.e. a right multiplication of the nxm matrix A and the 1xn vector) * * @param A an mxn matrix * @param v a nx1 vector * @return a mx1 vector output */ public static double[] matrixProduct(double[][] A, double[] v) throws Exception { if (v.length != A[0].length) { throw new Exception("Number of entries of v " + v.length + " does not match the number of columns of A " + A[0].length); } // Result length is the number of rows of A double[] result = new double[A.length]; for (int r = 0; r < result.length; r++) { result[r] = 0; for (int c = 0; c < v.length; c++) { result[r] += A[r][c] * v[c]; } } return result; } }