{"record":{"id":"0c53a2d734409ac5","repo":"TheAlgorithms/Go","slug":"matrices-are-not-compatible-for-subtraction","errorCode":null,"errorMessage":"matrices are not compatible for subtraction","messagePattern":"matrices are not compatible for subtraction","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"math/matrix/subtract.go","lineNumber":13,"sourceCode":"package matrix\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n)\n\n// Subtract subtracts two matrices.\nfunc (m1 Matrix[T]) Subtract(m2 Matrix[T]) (Matrix[T], error) {\n\t// Check if the matrices have the same dimensions.\n\tif !m1.MatchDimensions(m2) {\n\t\treturn Matrix[T]{}, errors.New(\"matrices are not compatible for subtraction\")\n\t}\n\n\t// Create a new matrix to store the result.\n\tvar zeroVal T\n\tresult := New(m1.Rows(), m1.Columns(), zeroVal)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel() // Make sure it's called to release resources even if no errors\n\n\tvar wg sync.WaitGroup\n\terrCh := make(chan error, 1)\n\n\tfor i := 0; i < m1.rows; i++ {\n\t\ti := i // Capture the loop variable for the goroutine\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor j := 0; j < m1.columns; j++ {","sourceCodeStart":1,"sourceCodeEnd":31,"githubUrl":"https://github.com/TheAlgorithms/Go/blob/5ba447ec5ff3d1213de65b92e726ee74c5d5cc19/math/matrix/subtract.go#L1-L31","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Ensure both matrices were created with the same rows and columns; check m1.Rows()==m2.Rows() && m1.Columns()==m2.Columns() first.","Pad/reshape the smaller matrix to match before subtracting.","Implement broadcasting manually with loops over Get/Set if vector-vs-matrix semantics are needed."],"exampleFix":"// before\n// a: 2x3, b: 2x2\nc, err := a.Subtract(b) // error\n\n// after\nb2, _ := math.NewFromElements([][]int{{1,0,0},{0,0,0}}) // 2x3\nc, err := a.Subtract(b2)","handlingStrategy":"validation","validationCode":"if a.Rows() != b.Rows() || a.Columns() != b.Columns() {\n    return fmt.Errorf(\"subtract shape mismatch %dx%d vs %dx%d\",\n        a.Rows(), a.Columns(), b.Rows(), b.Columns())\n}\nres, err := a.Subtract(b)","typeGuard":"func sameShape[T constraints.Integer](a, b math.Matrix[T]) bool {\n    return a.Rows() == b.Rows() && a.Columns() == b.Columns()\n}","tryCatchPattern":"res, err := a.Subtract(b)\nif err != nil {\n    return Matrix{}, fmt.Errorf(\"subtract: %w\", err)\n}","preventionTips":["Keep both operands derived from the same construction call so shapes stay locked.","Do not expect broadcasting; pad or loop manually for vector-vs-matrix cases.","Assert shapes in tests before running arithmetic pipelines."],"tags":["matrix","subtraction","dimension-mismatch","go"],"backgroundTag":"matrix-dimension-mismatch","analyzedSha":"5ba447ec5ff3d1213de65b92e726ee74c5d5cc19","analyzedAt":"2026-09-02T21:54:30.227Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-10T02:17:09.455Z"}