TheAlgorithms/Go · error

matrices are not compatible for addition

Error message

matrices are not compatible for addition

What it means

Returned by Matrix.Add when MatchDimensions reports the two operands have differing rows/columns; element-wise addition is undefined for matrices of unequal shape, so the operation aborts before allocating the result matrix.

Source

Thrown at math/matrix/add.go:18

// add.go
// description: Add two matrices
// time complexity: O(n^2)
// space complexity: O(n^2)

package matrix

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

// Add adds two matrices.
func (m1 Matrix[T]) Add(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 addition")
	}

	// 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. Verify m1.Rows()==m2.Rows() and m1.Columns()==m2.Columns() before calling Add
  2. Resize or pad one matrix if addition of different shapes is intended
  3. Use broadcasting-aware matrix libraries for shape-mismatched adds
Defensive patterns

Strategy: type-guard

When it happens

Trigger: Thrown at math/matrix/add.go:18 when the library encounters an invalid state.

Common situations: See trigger scenarios.


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