MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / Add

Method Add

math/matrix/add.go:15–69  ·  view source on GitHub ↗

Add adds two matrices.

(m2 Matrix[T])

Source from the content-addressed store, hash-verified

13
14// Add adds two matrices.
15func (m1 Matrix[T]) Add(m2 Matrix[T]) (Matrix[T], error) {
16 // Check if the matrices have the same dimensions.
17 if !m1.MatchDimensions(m2) {
18 return Matrix[T]{}, errors.New("matrices are not compatible for addition")
19 }
20
21 // Create a new matrix to store the result.
22 var zeroVal T
23 result := New(m1.Rows(), m1.Columns(), zeroVal)
24
25 ctx, cancel := context.WithCancel(context.Background())
26 defer cancel() // Make sure it's called to release resources even if no errors
27
28 var wg sync.WaitGroup
29 errCh := make(chan error, 1)
30
31 for i := 0; i < m1.rows; i++ {
32 i := i // Capture the loop variable for the goroutine
33 wg.Add(1)
34 go func() {
35 defer wg.Done()
36 for j := 0; j < m1.columns; j++ {
37 select {
38 case <-ctx.Done():
39 return // Context canceled; return without an error
40 default:
41 }
42
43 sum := m1.elements[i][j] + m2.elements[i][j]
44 err := result.Set(i, j, sum)
45 if err != nil {
46 cancel() // Cancel the context on error
47 select {
48 case errCh <- err:
49 default:
50 }
51 return
52 }
53 }
54 }()
55 }
56
57 // Wait for all goroutines to finish
58 go func() {
59 wg.Wait()
60 close(errCh)
61 }()
62
63 // Check for any errors
64 if err := <-errCh; err != nil {
65 return Matrix[T]{}, err
66 }
67
68 return result, nil
69}

Callers

nothing calls this directly

Calls 6

MatchDimensionsMethod · 0.95
RowsMethod · 0.95
ColumnsMethod · 0.95
SetMethod · 0.80
NewFunction · 0.70
AddMethod · 0.65

Tested by

no test coverage detected