getSubmatrix method

List<Float64List> getSubmatrix (List<Float64List> matrix, int row1, int row2, int col1, int col2, bool negLevels)

Returns the submatrix of matrix defined by row1, row2, col1, col2. row2 and col2 are exclusive indices! row1/2 and col1/2 need not be ordered. 0<=row1,2<=sizef1, 0<=col1,2<=size- An exception is thrown in case of errors, e.g. indices out of range. The result may have 0 elements, depending on input indices. The result has (col2 - col1).abs() columns and (row2 - row1).abs() rows. negLevels = true means only negative values are retained, false means only positive values are retained, the respective others are set to 0 (= positive and negative envelopes, e.g. usefull for contour or 3D surface display of a matrix). Null means all values are retained without change. Returns the list of rows of the submatrix.

Implementation

static List<Float64List> getSubmatrix(List<Float64List> matrix, int row1,
    int row2, int col1, int col2, bool negLevels) {
  int size = matrix[0].length; // assuming all rows have the same length
  int sizef1 = matrix.length;
  if ((row1 == 0 && row2 == sizef1) && col1 == 0 && col2 == sizef1)
    return matrix; // full matrix

  if (row1 < 0 ||
      row2 < 0 ||
      col1 < 0 ||
      col2 < 0 ||
      row1 > sizef1 ||
      row2 > sizef1 ||
      col1 > size ||
      col2 > size)
    throw new Exception("CompressedData2D: Submatrix out of bounds");

  int nrows = (row2 - row1).abs();
  int ncols = (col2 - col1).abs();

  int firstRow = row1;
  int endRow = row2;
  if (row1 > row2) {
    firstRow = row2;
    endRow = row1;
  }

  int firstCol = col1;
  if (col1 > col2) {
    firstCol = col2;
  }

  Float64List resultRow;
  Float64List inputRow;
  List<Float64List> result = new List<Float64List>(nrows);
  double curval;
  int destrow = 0;
  for (int i = firstRow; i < endRow; i++) {
    inputRow = matrix[i];
    resultRow = new Float64List(ncols); // will contain zeroes!
    for (int j = 0; j < ncols; j++) {
      curval = inputRow[firstCol + j];
      if (negLevels != null) {
        if (negLevels && curval > 0 || !negLevels && curval < 0) curval = 0.0;
      }
      resultRow[j] = curval;
    }
    result[destrow++] = resultRow;
  }
  return result;
}