I have found a way to delete rows and columns from a 2D double matrix using Apache Commons Math. My condition for deletion was if a column or row had all zeroes. Is there a similar way for integer matrix? I want to avoid creating copies of large double matrices.
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();
}