如何将一维double[]转换为矩阵形式的二维double[][]?
将一维double[]转换为二维double[][]的实现方法
你可以通过索引计算+循环赋值的方式实现,这个逻辑和元素类型无关,不管是int还是double数组都适用。核心是根据目标矩阵的行列数,把一维数组的每个元素映射到二维数组的对应位置。
实现步骤与代码示例
- 定义目标矩阵的行数
rows、列数cols,并确保一维数组长度等于rows * cols(避免数组越界) - 创建对应大小的二维
double[][]数组 - 遍历一维数组,通过整数除法和取余计算元素在二维数组中的行、列索引,完成赋值
// 待转换的一维double数组(用变量替代实际数值) double[] oneDArray = ...; // 目标矩阵的行数和列数(自定义变量) int targetRows = ...; int targetCols = ...; // 校验数组长度匹配性 if (oneDArray.length != targetRows * targetCols) { throw new IllegalArgumentException("一维数组长度与目标矩阵行列乘积不匹配"); } // 初始化二维矩阵 double[][] twoDMatrix = new double[targetRows][targetCols]; // 遍历赋值 for (int i = 0; i < oneDArray.length; i++) { // 计算当前元素对应的行索引:整数除法 int row = i / targetCols; // 计算当前元素对应的列索引:取余运算 int col = i % targetCols; twoDMatrix[row][col] = oneDArray[i]; }
示例验证
比如你提到的[1, 2, 3, 4]转2*2矩阵的场景:
- 设置
targetRows = 2,targetCols = 2 - 循环中:
- i=0 → row=0/2=0,col=0%2=0 →
twoDMatrix[0][0] = 1 - i=1 → row=1/2=0,col=1%2=1 →
twoDMatrix[0][1] = 2 - i=2 → row=2/2=1,col=2%2=0 →
twoDMatrix[1][0] = 3 - i=3 → row=3/2=1,col=3%2=1 →
twoDMatrix[1][1] = 4
- i=0 → row=0/2=0,col=0%2=0 →
最终得到的二维矩阵就是你需要的结构。
内容的提问来源于stack exchange,提问作者Alison Lee
相关产品推荐
相关产品推荐

