Add adds two matrices.
(m2 Matrix[T])
| 13 | |
| 14 | // Add adds two matrices. |
| 15 | func (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 | } |