subMatrix method
Extracts a subMatrix from the given matrix using the specified row and column indices or ranges.
rowIndices: Optional list of integers representing the row indices to include in the subMatrix.columnIndices: Optional list of integers representing the column indices to include in the subMatrix.rowRange: Optional string representing the row range (e.g. "1:3").colRange: Optional string representing the column range (e.g. "1:3").rowStart: Optional start index of the row range.rowEnd: Optional end index of the row range.colStart: Optional start index of the column range.colEnd: Optional end index of the column range.
Returns a new matrix containing the specified subMatrix.
Example:
var matrix = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
var subMatrix = matrix.subMatrix(rowList: [0, 2], colList: [1, 2]);
print(subMatrix);
// Output:
// 2 3
// 8 9
Implementation
Matrix subMatrix(
{List<int>? rowIndices,
List<int>? columnIndices,
String rowRange = '',
String colRange = '',
int? rowStart,
int? rowEnd,
int? colStart,
int? colEnd}) {
// If no row indices are provided, default to all rows
// If rowStart or rowEnd is provided, use these to create the list
final rowIndices_ = rowIndices ??
(rowStart != null && rowEnd != null
? List.generate(rowEnd - rowStart + 1, (i) => rowStart + i)
: (rowRange.isNotEmpty
? _Utils.parseRange(rowRange, rowCount)
: (rowStart != null
? List.generate(rowCount - rowStart, (i) => rowStart + i)
: (rowEnd != null
? List.generate(rowEnd + 1, (i) => i)
: List.generate(rowCount, (i) => i)))));
// If no column indices are provided, default to all columns
// If colStart or colEnd is provided, use these to create the list
final colIndices_ = columnIndices ??
(colStart != null && colEnd != null
? List.generate(colEnd - colStart + 1, (i) => colStart + i)
: (colRange.isNotEmpty
? _Utils.parseRange(colRange, columnCount)
: (colStart != null
? List.generate(columnCount - colStart, (i) => colStart + i)
: (colEnd != null
? List.generate(colEnd + 1, (i) => i)
: List.generate(columnCount, (i) => i)))));
if (rowIndices_.any((i) => i < 0 || i >= rowCount)) {
throw Exception('Row indices are out of range');
}
if (colIndices_.any((i) => i < 0 || i >= columnCount)) {
throw Exception('Column indices are out of range');
}
List<List<dynamic>> newData = rowIndices_.map((rowIndex) {
return colIndices_.map((colIndex) => _data[rowIndex][colIndex]).toList();
}).toList();
return Matrix(newData);
}