首页 > 解决方案 > 如何使用 insertColumn(int j, 向量列)

问题描述

我只需要在矩阵中插入零的行和列

试图从网络搜索中获取示例

ArrayList<double [][]> al = new ArrayList<>();
for (int i1= 0; i1<=i; i1++)
    al.add(k);

System.out.println(al.size());
double[][] firstMatrix = al.get(i);
double [][] matrix1 = al.get(i); 
double [][] matrix2 = al.get(i); 
Matrix Matrix1 = new Matrix (matrix1);
Matrix1.show();
System.out.println(); 
Matrix1.insertColumn(0,0.0, 0.0, 0.0, 0.0);
Matrix1.show();
System.out.println();

标签: javaarrays

解决方案


您的问题归结为向 Java 数组添加新列/行。这本身是不可能的,因为你的数组有一个确切的内存区域分配给它,你需要一个更大的内存区域来存储结果数组,所以,解决方案是创建一个新数组并以这种方式解决问题:

添加一行

double[][] addRow(double[][] input, int where) {
    double[][] output = new double[input.length + 1][input[0].length];
    for (int rIndex = 0; rIndex < output.length; rIndex++) {
        for (int cIndex = 0; cIndex < output[0].length; cIndex++) {
            if (rIndex < where) output[rIndex][cIndex] = input[rIndex][cIndex];
            else if (rIndex == where) output[rIndex][cIndex] = 0;
            else output[rIndex][cIndex] = input[rIndex - 1][cIndex];
        }
    }
    return output;
}

添加列

double[][] addColumn(double [][]input, int where) {
    double[][] output = new double[input.length][input[0].length + 1];
    for (int rIndex = 0; rIndex < output.length; rIndex++) {
        for (int cIndex = 0; cIndex < output[0].length; cIndex++) {
            if (cIndex < where) output[rIndex][cIndex] = input[rIndex][cIndex];
            else if (cIndex == where) output[rIndex][cIndex] = 0;
            else output[rIndex][cIndex] = input[rIndex][cIndex - 1];
        }
    }
    return output;
}

并确保将这些方法的结果分配给您用作数据源的任何变量/成员。


推荐阅读