首页 > 解决方案 > 用一维数组java填充二维数组

问题描述

我有一个矩阵和一个数组,我想从数组值中填充矩阵。

float [][] mat = new float [m][n];
float [] array= new float [3];

例如 :

arr = {1, 2, 3}

尺寸为 4*4 的垫子

垫=

        {1, 2, 3, 1

         2, 3, 1, 2

         3, 1, 2, 3

         1, 2, 3, 1}

填充矩阵的方法是什么?

标签: javamatrix

解决方案


根据您的示例,您希望使用数组中的值在矩阵中插入一行。

首先,让我们构建矩阵和数组值:

int m = 3;
int n = 5;
float[][] mat = new float[m][n];
float[] array = {1,2,3,4};
    

然后,迭代矩阵以准备更新:

for(int i = 0; i < m; i++){
    for(int j = 0; j < n; j++){
        // update here
    }
}

所以,你想要的是使用数组来设置值,当你到达终点时,你重新开始。我看到了两种解决方案:

使用索引

我们增加它,但是当我们达到数组的长度时,使用模返回“0”。

int currentIndex = 0;
for(int i = 0; i < m; i++){
    for(int j = 0; j < n; j++){
        mat[i][j] = array[currentIndex];
        currentIndex = (currentIndex + 1 ) % array.length;
    }
}

使用矩阵坐标

或者您可以通过对矩阵的两个索引求和然后再次使用模数来获得索引,这允许在没有循环的情况下更新任何值,(如果需要)

for(int i = 0; i < m; i++){
    for(int j = 0; j < n; j++){
        mat[i][j] = array[(i+j)%array.length];
    }
}

此解决方案的一个问题是,您将无法获得矩阵的正确输出,m + n > Integer.MAX_VALUE因为总和将给出负值,从而给出不正确的索引。

输出

您可以使用以下命令查看结果:

System.out.println(java.util.Arrays.deepToString(mat));

两种解决方案都给出:

[
    [1.0, 2.0, 3.0, 4.0, 1.0],
    [2.0, 3.0, 4.0, 1.0, 2.0],
    [3.0, 4.0, 1.0, 2.0, 3.0]
]

推荐阅读