Multiplies two matrices using an implementation faster than the straightforward one. - Java java.lang

Java examples for java.lang:Math Matrix

Description

Multiplies two matrices using an implementation faster than the straightforward one.

Demo Code


//package com.java2s;

public class Main {
    /**//from   w  w w  . j  a  v  a2s .  c  om
     * Multiplies two matrices using an implementation faster than the
     * straightforward one. The multiplication order is A * B and the results is
     * a matrix.
     *
     * @param a   Matrix of doubles.
     * @param b   Matrix of doubles.
     * @return   Matrix computed by matrix multiplication of the two matrices.
     */
    public static double[][] multiplyMatrices(double[][] a, double[][] b) {

        double[][] c = new double[a.length][b[0].length];
        for (int i = 0; i < a.length; i++) {
            for (int k = 0; k < b.length; k++) {
                for (int j = 0; j < b[0].length; j++) {
                    c[i][j] += a[i][k] * b[k][j];
                }
            }
        }

        return c;
    }

    /**
     * Multiplies two matrices using an implementation faster than the
     * straightforward one. The multiplication order is A * B and the result is
     * a matrix.
     *
     * @param a   Matrix of integers.
     * @param b   Matrix of integers.
     * @return   Matrix result of matrix multiplication of the two matrices.
     */
    public static double[][] multiplyMatrices(int[][] a, int[][] b) {

        double[][] c = new double[a.length][b[0].length];
        for (int i = 0; i < a.length; i++) {
            for (int k = 0; k < b.length; k++) {
                for (int j = 0; j < b[0].length; j++) {
                    c[i][j] += (double) a[i][k] * (double) b[k][j];
                }
            }
        }

        return c;
    }
}

Related Tutorials