TheAlgorithms/Go · error

matrices are not compatible for subtraction

Error message

matrices are not compatible for subtraction

What it means

Returned by Matrix.Subtract when MatchDimensions reports the two operands differ in rows or columns; element-wise subtraction requires identical shapes, so the operation aborts before allocating the result matrix.

Source

Thrown at math/matrix/subtract.go:13

package matrix

import (
	"context"
	"errors"
	"sync"
)

// Subtract subtracts two matrices.
func (m1 Matrix[T]) Subtract(m2 Matrix[T]) (Matrix[T], error) {
	// Check if the matrices have the same dimensions.
	if !m1.MatchDimensions(m2) {
		return Matrix[T]{}, errors.New("matrices are not compatible for subtraction")
	}

	// Create a new matrix to store the result.
	var zeroVal T
	result := New(m1.Rows(), m1.Columns(), zeroVal)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel() // Make sure it's called to release resources even if no errors

	var wg sync.WaitGroup
	errCh := make(chan error, 1)

	for i := 0; i < m1.rows; i++ {
		i := i // Capture the loop variable for the goroutine
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < m1.columns; j++ {

View on GitHub (pinned to 5ba447ec5f)

Solutions

  1. Ensure both matrices were created with the same rows and columns; check m1.Rows()==m2.Rows() && m1.Columns()==m2.Columns() first.
  2. Pad/reshape the smaller matrix to match before subtracting.
  3. Implement broadcasting manually with loops over Get/Set if vector-vs-matrix semantics are needed.

Example fix

// before
// a: 2x3, b: 2x2
c, err := a.Subtract(b) // error

// after
b2, _ := math.NewFromElements([][]int{{1,0,0},{0,0,0}}) // 2x3
c, err := a.Subtract(b2)
Defensive patterns

Strategy: validation

Validate before calling

if a.Rows() != b.Rows() || a.Columns() != b.Columns() {
    return fmt.Errorf("subtract shape mismatch %dx%d vs %dx%d",
        a.Rows(), a.Columns(), b.Rows(), b.Columns())
}
res, err := a.Subtract(b)

Type guard

func sameShape[T constraints.Integer](a, b math.Matrix[T]) bool {
    return a.Rows() == b.Rows() && a.Columns() == b.Columns()
}

Try / catch

res, err := a.Subtract(b)
if err != nil {
    return Matrix{}, fmt.Errorf("subtract: %w", err)
}

Prevention

When it happens

Trigger: Calling m1.Subtract(m2) where shapes differ, e.g. (2x3) minus (3x2), or subtracting a result of multiplication from the original operands with different shapes.

Common situations: Mixing matrices built from datasets of different sizes; a broadcast-style expectation (subtracting a row vector from a matrix) that the library does not support; shape drift from earlier submatrix/slice operations.

Related errors


AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02). Data as JSON: /api/errors/0c53a2d734409ac5. Report an issue: GitHub.