Java 中使用 2D ArrayLists 的矩阵乘法 [英] Matrix multiplication in Java using 2D ArrayLists

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

问题描述

我正在尝试用 Java 实现一个简单的矩阵乘法,我将矩阵存储在二维 ArrayList 中.似乎错误是由嵌套的 for 循环内的矩阵 Result 的设置引起的,但我不明白为什么.

I am trying to implement a simple matrix multiplication in Java, where I am storing the matrices in two-dimensional ArrayLists. It would seem the error is caused by the setting of matrix Result, inside the nested for loop, but I do not understand why.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;

public class Test {
    public static void main(String args[]) {
        int n = 2;

        ArrayList<ArrayList<Integer>> Result =
                new ArrayList<ArrayList<Integer>>(
                        Collections.nCopies(n, new ArrayList<Integer>(
                                Collections.nCopies(n, 0))));
        ArrayList<ArrayList<Integer>> A = new ArrayList<ArrayList<Integer>>();
        ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>>();

        A.add(new ArrayList<Integer>(Arrays.asList(1, 6)));
        A.add(new ArrayList<Integer>(Arrays.asList(2, 2)));
        B.add(new ArrayList<Integer>(Arrays.asList(0, 9)));
        B.add(new ArrayList<Integer>(Arrays.asList(5, 6)));

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                for (int k = 0; k < n; k++) {
                    int val = A.get(i).get(k) * B.get(k).get(j);
                    Result.get(i).set(j, Result.get(i).get(j) + val);
                }
            }
        }
    }
}

代码产生的结果:

A * B = [[40, 75], [40, 75]]

实际上应该是:

A * B = [[30, 45], [10, 30]]

推荐答案

Result 未正确初始化.

ArrayList<ArrayList<Integer>> Result = new ArrayList<ArrayList<Integer>>(
    Collections.nCopies(n,
        new ArrayList<Integer>(Collections.nCopies(n, 0))));

这将创建一个矩阵,其中两行(或列,取决于你怎么看)实际上是同一行(列),被引用了两次.

This creates a matrix where two rows (or columns, depending how you look at that) are in fact same row (column), referenced twice.

你可以像这样初始化Result:

List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < n; i++) {
    result.add(new ArrayList<>(Collections.nCopies(n, 0)));
}

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

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