我找到了一种使用Apache Commons Math从2D double 矩阵中删除行和列的方法。我删除的条件是列或行是否全部为零。整数矩阵有类似的方法吗?我想避免创建大型双矩阵的副本。
public double[][] removeRowsAndColumnsWithAllZeroes(double[][] data)
{
//double[][] data =
// {
// {1, 0, 0},
// {1, 1, 0},
// {1, 1, 0},
// {0, 1, 0},
// {0, 0, 0}};
RealMatrix m = MatrixUtils.createRealMatrix(data);
List<Integer> rowList = new ArrayList<Integer>();
List<Integer> colList = new ArrayList<Integer>();
for (int i = 0; i < m.getRowDimension(); i++)
{
double total = 0;
for (double r : m.getRow(i))
total += r;
if (total == 0)
continue;
rowList.add(i);
}
for (int i = 0; i < m.getColumnDimension(); i++)
{
double total = 0;
for (double r : m.getColumn(i))
total += r;
if (total == 0)
continue;
colList.add(i);
}
int[] columns = new int[colList.size()];
int[] rows = new int[rowList.size()];
for (int i = 0; i < columns.length; i++)
columns[i] = colList.get(i);
for (int i = 0; i < rows.length; i++)
rows[i] = rowList.get(i);
System.out.println(m);
//Array2DRowRealMatrix{{1.0,0.0,0.0},{1.0,1.0,0.0},{1.0,1.0,0.0},{0.0,1.0,0.0},{0.0,0.0,0.0}}
System.out.println("Rows:\t" + m.getRowDimension() + "\tColumns:\t" + m.getColumnDimension());
// Rows: 5 Columns: 3
RealMatrix n = m.getSubMatrix(rows, columns);
System.out.println(n);
// Array2DRowRealMatrix{{1.0,0.0},{1.0,1.0},{1.0,1.0},{0.0,1.0}}
System.out.println("Rows:\t" + n.getRowDimension() + "\tColumns:\t" + n.getColumnDimension());
// Rows: 4 Columns: 2
return n.getData();
}
答案 0 :(得分:0)
作为示例,下面的代码标识了具有全零的行和列。 将4x3阵列作为输入。 注意,ArrayList可以转换为数组并反转。
public class ZeroesIn2Darray{
static int dataArr[][] = {{1,0,0},
{0,0,0},
{1,0,0},
{0,0,0}};
public static void main(String[] args){
int rowCount = dataArr.length;
int colCount = dataArr[0].length;
int[] rowsForDeletion = new int[rowCount]; //stores identified row#s
int indexRowsForDeletion = 0;
int[] colsForDeletion = new int[colCount]; //stores identified col#s
int indexColsForDeletion = 0;
// identify rows with all 0s
for(int i=0; i<rowCount; i++){
int rowTotal = 0;
for(int j=0; j<colCount; j++)
rowTotal += dataArr[i][j]; //gets sum for row=i
if (rowTotal == 0)
rowsForDeletion[indexRowsForDeletion++] = i;
}
// print the identified rows
System.out.print("Rows with all zeroes: ");
for (int k=0;k<indexRowsForDeletion;k++)
System.out.print(rowsForDeletion[k] + " ");
System.out.println();
// identify cols with all 0s
for(int j=0; j<colCount; j++){
int colTotal = 0;
for(int i=0; i<rowCount; i++)
colTotal += dataArr[i][j]; //gets sum for col=j
if (colTotal == 0)
colsForDeletion[indexColsForDeletion++] = j;
}
// print the identified cols
System.out.print("Cols with all zeroes: ");
for (int l=0;l<indexColsForDeletion;l++)
System.out.print(colsForDeletion[l] + " ");
System.out.println();
} //end of main()
} //end of class