reshapeList method

Matrix reshapeList(
  1. List<int> newShape
)

Reshapes the matrix to have the specified shape provided in the form of a list.

newShape: List of integers representing the new shape (rows and columns).

Returns a new matrix with the specified shape.

Example:

var matrix = Matrix([[1, 2], [3, 4]]);
var reshaped = matrix.reshapeList([1, 4]);
print(reshaped);
// Output:
// 1  2  3  4

Implementation

Matrix reshapeList(List<int> newShape) {
  int newRows = newShape[0];
  int newCols = newShape[1];
  int totalElements = rowCount * columnCount;
  if (newRows * newCols != totalElements) {
    throw Exception('Cannot reshape matrix to specified shape');
  }

  List<List<dynamic>> newData = [];

  for (int i = 0; i < newRows; i++) {
    List<dynamic> row = [];
    for (int j = 0; j < newCols; j++) {
      int index = i * newCols + j;
      int rowIndex = index ~/ columnCount;
      int colIndex = index % columnCount;
      row.add(_data[rowIndex][colIndex]);
    }
    newData.add(row);
  }

  return Matrix(newData);
}