Java 8矩阵*向量乘法 [英] Java 8 matrix * vector multiplication

查看:96
本文介绍了Java 8矩阵*向量乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Java 8中是否有一种更简洁的方式来执行以下操作:

I'm wondering if there is a more condensed way of doing the following in Java 8 with streams:

public static double[] multiply(double[][] matrix, double[] vector) {
    int rows = matrix.length;
    int columns = matrix[0].length;

    double[] result = new double[rows];

    for (int row = 0; row < rows; row++) {
        double sum = 0;
        for (int column = 0; column < columns; column++) {
            sum += matrix[row][column]
                    * vector[column];
        }
        result[row] = sum;
    }
    return result;
}

进行编辑.我收到了很好的答案,但是性能比旧的实现慢了大约10倍,因此我在这里添加了测试代码,以防有人要调查它:

Making an Edit. I received a very good answer, however the performance is about 10X slower than the old implementation, so I'm adding the test code here in case anyone wants to investigate it:

@Test
public void profile() {
    long start;
    long stop;
    int tenmillion = 10000000;
    double[] vector = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    double[][] matrix = new double[tenmillion][10];

    for (int i = 0; i < tenmillion; i++) {
        matrix[i] = vector.clone();
    }
    start = System.currentTimeMillis();
    multiply(matrix, vector);
    stop = System.currentTimeMillis();
 }

推荐答案

使用Stream的直接方法如下:

A direct way using Stream would be the following:

public static double[] multiply(double[][] matrix, double[] vector) {
    return Arrays.stream(matrix)
                 .mapToDouble(row -> 
                    IntStream.range(0, row.length)
                             .mapToDouble(col -> row[col] * vector[col])
                             .sum()
                 ).toArray();
}

这将创建矩阵(Stream<double[]>)的每一行的Stream,然后将每一行映射到使用vector数组计算乘积所得的double值.

This creates a Stream of each row of the matrix (Stream<double[]>), then maps each row to the double value resulting of calculating the product with the vector array.

我们必须在索引上使用Stream来计算乘积,因为不幸的是,没有内置的功能可以将两个Stream压缩在一起.

We have to use a Stream over the indexes to calculate the product because there are unfortunately no built-in facility to zip two Streams together.

这篇关于Java 8矩阵*向量乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆