Skip to content

Instantly share code, notes, and snippets.

@vwxyzjn
Last active April 8, 2022 20:16
Show Gist options
  • Save vwxyzjn/bcac5f97b5abb7708773a28b82a809b4 to your computer and use it in GitHub Desktop.
Save vwxyzjn/bcac5f97b5abb7708773a28b82a809b4 to your computer and use it in GitHub Desktop.
πŸ‘ *CORRECT* Simple Matrix multiplication and transpostion with Go (https://play.golang.org/p/uVJLR8qAxv3)
package main
import (
"errors"
"fmt"
)
func main() {
X := [][]float32{
[]float32{1.0, 2.0, 3.0},
[]float32{4.0, 5.0, 6.0},
}
w := [][]float32{
[]float32{0.5, 0.2, 0.7},
[]float32{0.5, 0.8, 0.3},
}
out, _ := multiply(X, transpose(w))
fmt.Println(out)
}
func transpose(x [][]float32) [][]float32 {
out := make([][]float32, len(x[0]))
for i := 0; i < len(x); i += 1 {
for j := 0; j < len(x[0]); j += 1 {
out[j] = append(out[j], x[i][j])
}
}
return out
}
func multiply(x, y [][]float32) ([][]float32, error) {
if len(x[0]) != len(y) {
return nil, errors.New("Can't do matrix multiplication.")
}
out := make([][]float32, len(x))
for i := 0; i < len(x); i++ {
out[i] = make([]float32, len(y[0]))
for j := 0; j < len(y[0]); j++ {
for k := 0; k < len(y); k++ {
out[i][j] += x[i][k] * y[k][j]
}
}
}
return out, nil
}
@vwxyzjn
Copy link
Author

vwxyzjn commented Dec 4, 2018

You can test it in https://play.golang.org/p/uVJLR8qAxv3

Notice there are 3 loops, which is also confirmed in an implementation in python (https://www.programiz.com/python-programming/examples/multiply-matrix). A more mathy version can be found here: (https://en.wikipedia.org/wiki/Matrix_multiplication)

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment