views:

288

answers:

1

Can anyone tell me how you can delete columns from a matrix using the Colt library?

TIA.

A: 

There is no explicit method to delete a column, but you can create a view of the original matrix that contains all columns but the one you would like to have removed.

/**
 * Returns a view of the original matrix that contains all rows and all columns
 * except for the specified column.
 *
 * The view is backed by the original matrix, that is, all changes to the
 * returned matrix will be reflected by the original matrix.
 *
 * @param src The matrix to have a column "removed".
 * @param colIdx The index of the column to be hidden
 *        ({@code 0 <= colIdx < src.columns()} .
 * @return A view of the original matrix with column {@code colIdx} removed.
 */
public DoubleMatrix2D hideColumn(final DoubleMatrix2D src, final int colIdx) {
    // create array of column indices to be preserved
    final int[] keepColumns = new int[src.columns() - 1];
    for (int i = 0; i < keepColumns.length; i++) {
        keepColumns[i] = ((i < colIdx) ? i : i + 1);
    }

    return src.viewSelection(null /* keep ALL rows */, keepColumns);
}
janko