split method
Splits the matrix into smaller matrices along the specified axis.
axis: The axis along which to split the matrix (0 for rows, 1 for columns).
splits: The number of equally sized subMatrices to split the matrix into.
Returns a list of new matrices resulting from the split.
Example:
var matrix = Matrix([[1, 2], [3, 4], [5, 6]]);
var splitMatrixList = matrix.split(0, 3);
print(splitMatrixList);
// Output:
// [ 1 2 ]
// [ 3 4 ]
// [ 5 6 ]
Implementation
List<Matrix> split(int axis, int splits) {
if (axis < 0 || axis > 1) {
throw Exception("Invalid axis value, axis must be 0 or 1");
}
if (splits <= 0) {
throw Exception("Splits must be a positive integer");
}
if (axis == 0 && rowCount % splits != 0) {
throw Exception("Number of rows is not divisible by splits");
}
if (axis == 1 && columnCount % splits != 0) {
throw Exception("Number of columns is not divisible by splits");
}
List<Matrix> result = [];
if (axis == 0) {
int chunkSize = rowCount ~/ splits;
for (int i = 0; i < rowCount; i += chunkSize) {
List<List<dynamic>> chunkData = toList().sublist(i, i + chunkSize);
result.add(Matrix(chunkData));
}
} else {
int chunkSize = columnCount ~/ splits;
for (int j = 0; j < columnCount; j += chunkSize) {
List<List<dynamic>> chunkData = List.generate(rowCount, (_) => []);
for (int i = 0; i < rowCount; i++) {
chunkData[i].addAll(this[i].sublist(j, j + chunkSize));
}
result.add(Matrix(chunkData));
}
}
return result;
}