copyFrom method

void copyFrom(
  1. Matrix other, {
  2. bool resize = false,
  3. bool retainSize = false,
})

Copies the elements from another matrix into this matrix.

  • other: The matrix to copy elements from.
  • resize: Optional boolean flag to resize this matrix to the shape of the other matrix.
    • If resize is true, the current matrix will be resized to the shape of the other matrix before the elements are copied.
    • If resize is false, the current matrix will not be resized.
  • retainSize: Optional boolean flag to retain the original size of this matrix while copying.
    • If retainSize is true, the current matrix will retain its original size, and only elements from the other matrix that can fit will be copied.
    • If retainSize is false, the current matrix will be resized to the shape of the other matrix before the elements are copied.

If both resize and retainSize are set to true, an exception will be thrown because this is a contradictory situation.

If resize is true and retainSize is false (default), this matrix will be resized to the size of the other matrix before copying.

If resize is false (default) and retainSize is true, this matrix will retain its original size, and only elements from the other matrix that can fit will be copied.

If resize and retainSize are both set to false (default), and the matrices have different shapes, an exception will be thrown.

Example 1:

var matrixA = Matrix([[1, 2], [3, 4]]);
var matrixB = Matrix([[5, 6], [7, 8], [9, 10]]);
matrixA.copyFrom(matrixB, resize: true);
print(matrixA);
// Output:
// 5  6
// 7  8
// 9 10

Example 2:

var matrixA = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
var matrixB = Matrix([[10, 11], [12, 13]]);
matrixA.copyFrom(matrixB, retainSize: true);
print(matrixA);
// Output:
// 10 11 3
// 12 13 6
// 7  8  9

Implementation

void copyFrom(Matrix other, {bool resize = false, bool retainSize = false}) {
  if (resize && retainSize) {
    throw Exception("resize and retainSize cannot both be true");
  }

  if (resize && !retainSize) {
    _data = List.generate(other.rowCount,
        (i) => List.filled(other.columnCount, Complex.zero()));
  }

  if (!resize && retainSize) {
    num copyRowCount = math.min(rowCount, other.rowCount);
    num copyColumnCount = math.min(columnCount, other.columnCount);

    for (int i = 0; i < copyRowCount; i++) {
      for (int j = 0; j < copyColumnCount; j++) {
        this[i][j] = other[i][j];
      }
    }
  } else if (!resize && !retainSize) {
    if (rowCount != other.rowCount || columnCount != other.columnCount) {
      throw Exception("Matrices have different shapes");
    }

    for (int i = 0; i < rowCount; i++) {
      for (int j = 0; j < columnCount; j++) {
        this[i][j] = other[i][j];
      }
    }
  }
}