java - 如何使用 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();
解决方案
您的问题归结为向 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;
}
并确保将这些方法的结果分配给您用作数据源的任何变量/成员。
推荐阅读
- php - PHP - 将匿名函数分配给其自己函数内的变量并使用它
- angular - 如果没有数据模型,Angular Material 在列表之间的拖放
- kubernetes - 如何在远程集群中使用 NodePort 访问 kubernetes 仪表板进行测试?
- python - 复制总图像的 20%
- ruby - 处理带有可选参数的方法,后跟关键字参数列表
- bash - How to record shell interaction from a background script
- fortran - Fortran浮点改变整数值
- r - 根据其他列从列中提取值列表
- javascript - Autocomplete content after a pipe using javascript or JQuery
- javascript - 如何更新firestore子集合字段