Multiplies a matrix and a vector. - Java java.lang

Java examples for java.lang:Math Matrix

Description

Multiplies a matrix and a vector.

Demo Code


//package com.java2s;

public class Main {
    /**/*w  w  w  .j  a va 2 s .  c o  m*/
     * Multiplies a matrix and a vector. The multiplication order is: matrix *
     * vector. The result of multiplication is a vector.
     *
     * @param matrix   Matrix of doubles.
     * @param vector   Vector of doubles.
     * @return   Vector result of multiplication of the matrix and vector.
     */
    public static double[] multiplyMatrixAndVector(double[][] matrix,
            double[] vector) {

        double[] res = new double[matrix[0].length];
        for (int i = 0; i < vector.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                res[j] += matrix[i][j] * vector[i];
            }
        }

        return res;
    }

    /**
     * Multiplies a matrix and a vector. The multiplication order is: matrix *
     * vector. The result of multiplication is a vector.
     *
     * @param matrix   Matrix of integers.
     * @param vector   Vector of integers.
     * @return   Vector result of multiplication of the matrix and vector.
     */
    public static double[] multiplyMatrixAndVector(int[][] matrix,
            int[] vector) {

        double[] res = new double[matrix.length];
        for (int i = 0; i < vector.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                res[j] += (double) matrix[i][j] * (double) vector[i];
            }
        }

        return res;
    }
}

Related Tutorials