{"record":{"id":"36aa8b7402151b1d","repo":"TheAlgorithms/Go","slug":"matrices-are-not-compatible-for-addition","errorCode":null,"errorMessage":"matrices are not compatible for addition","messagePattern":"matrices are not compatible for addition","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"math/matrix/add.go","lineNumber":18,"sourceCode":"// add.go\n// description: Add two matrices\n// time complexity: O(n^2)\n// space complexity: O(n^2)\n\npackage matrix\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n)\n\n// Add adds two matrices.\nfunc (m1 Matrix[T]) Add(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 addition\")\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":36,"githubUrl":"https://github.com/TheAlgorithms/Go/blob/5ba447ec5ff3d1213de65b92e726ee74c5d5cc19/math/matrix/add.go#L1-L36","documentation":"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.","triggerScenarios":"Thrown at math/matrix/add.go:18 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":["Verify m1.Rows()==m2.Rows() and m1.Columns()==m2.Columns() before calling Add","Resize or pad one matrix if addition of different shapes is intended","Use broadcasting-aware matrix libraries for shape-mismatched adds"],"exampleFix":null,"handlingStrategy":"type-guard","validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"5ba447ec5ff3d1213de65b92e726ee74c5d5cc19","analyzedAt":"2026-09-02T21:54:30.227Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-10T02:17:09.455Z"}