binaryOperation<O, R> method

Tensor<R> binaryOperation<O, R>(
  1. Tensor<O> other,
  2. Map2<T, O, R> function, {
  3. DataType<R>? type,
  4. Tensor<R>? target,
})

Performs a binary element-wise operation function on this tensor and other and stores the result into target or (if missing) into a newly created one.

Implementation

Tensor<R> binaryOperation<O, R>(Tensor<O> other, Map2<T, O, R> function,
    {DataType<R>? type, Tensor<R>? target}) {
  final (thisLayout, otherLayout) = layout.broadcast(other.layout);
  final thisIterator = thisLayout.indices.iterator;
  final otherIterator = otherLayout.indices.iterator;
  final thisData = data, otherData = other.data;
  if (target == null) {
    // Create a new tensor.
    final resultType = type ?? DataType.fromType<R>();
    final resultData = resultType.newList(thisLayout.length);
    for (var i = 0;
        i < thisLayout.length &&
            thisIterator.moveNext() &&
            otherIterator.moveNext();
        i++) {
      resultData[i] = function(
        thisData[thisIterator.current],
        otherData[otherIterator.current],
      );
    }
    return Tensor<R>.internal(
      type: resultType,
      layout: Layout(shape: thisLayout.shape),
      data: resultData,
    );
  } else {
    // Perform the operation into another one (possibly in-place).
    LayoutError.checkEqualShape(layout, target.layout, 'target');
    final targetData = target.data;
    final targetIterator = target.layout.indices.iterator;
    while (targetIterator.moveNext() &&
        thisIterator.moveNext() &&
        otherIterator.moveNext()) {
      targetData[targetIterator.current] = function(
        thisData[thisIterator.current],
        otherData[otherIterator.current],
      );
    }
    return target;
  }
}