To implement matrix operations like matrix addition and multiplication in Go, you can follow the steps below:
type Matrix struct {
rows int
columns int
data [][]float64
}
func NewMatrix(rows, columns int, data [][]float64) *Matrix {
if len(data) != rows || len(data[0]) != columns {
// Handle invalid input
return nil
}
m := Matrix{rows: rows, columns: columns}
m.data = make([][]float64, rows)
for i := 0; i < rows; i++ {
m.data[i] = make([]float64, columns)
copy(m.data[i], data[i])
}
return &m
}
func MatrixAddition(a, b *Matrix) (*Matrix, error) {
if a.rows != b.rows || a.columns != b.columns {
return nil, fmt.Errorf("Matrices dimensions do not match")
}
result := NewMatrix(a.rows, a.columns, a.data)
for i := 0; i < a.rows; i++ {
for j := 0; j < a.columns; j++ {
result.data[i][j] += b.data[i][j]
}
}
return result, nil
}
func MatrixMultiplication(a, b *Matrix) (*Matrix, error) {
if a.columns != b.rows {
return nil, fmt.Errorf("Matrices dimensions do not match for multiplication")
}
result := NewMatrix(a.rows, b.columns, nil)
for i := 0; i < a.rows; i++ {
for j := 0; j < b.columns; j++ {
dotProduct := 0.0
for k := 0; k < a.columns; k++ {
dotProduct += a.data[i][k] * b.data[k][j]
}
result.data[i][j] = dotProduct
}
}
return result, nil
}
Note: The above implementation assumes well-formed input matrices. You may need to add additional error handling and input validation code as required.
Now, you can use the implemented functions to perform matrix operations:
func main() {
aData := [][]float64{{1, 2, 3}, {4, 5, 6}}
bData := [][]float64{{7, 8}, {9, 10}, {11, 12}}
a := NewMatrix(len(aData), len(aData[0]), aData)
b := NewMatrix(len(bData), len(bData[0]), bData)
result, err := MatrixAddition(a, b)
if err != nil {
log.Fatal(err)
}
fmt.Println("Addition Result:")
result.Print()
result, err = MatrixMultiplication(a, b)
if err != nil {
log.Fatal(err)
}
fmt.Println("Multiplication Result:")
result.Print()
}
This example demonstrates how to create matrices from data, perform matrix addition and multiplication, and print the results. You can further extend it to include more matrix operations or make the implementation more efficient as needed.