Created
April 9, 2018 20:15
-
-
Save JVero/f9d3a4d0193bff90fba36c1a8ab6d1e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"strconv" | |
"sync" | |
) | |
type Matrix struct { | |
width int | |
height int | |
values [][]float64 | |
} | |
func Empty(rowHeight int, columnWidth int) Matrix { | |
matVals := make([][]float64, rowHeight) | |
for row := range matVals { | |
matVals[row] = make([]float64, columnWidth) | |
} | |
return Matrix{rowHeight, columnWidth, matVals} | |
} | |
func (m *Matrix) assignValue(row int, column int, val float64) { | |
m.values[row][column] = val | |
} | |
func Eye(size int) Matrix { | |
returnMatrix := Empty(size, size) | |
for i := 0; i < size; i++ { | |
returnMatrix.assignValue(i, i, 1) | |
} | |
return returnMatrix | |
} | |
func (m Matrix) multiply(n Matrix) Matrix { | |
var retMat Matrix | |
var wg sync.WaitGroup | |
if len(m.values) == len(n.values[0]) { // C1 == R2 { | |
retMat = Empty(len(m.values), len(n.values[0])) | |
} else { | |
return Matrix{} | |
} | |
for i := range m.values { | |
wg.Add(1) | |
go func(ig int) { | |
defer wg.Done() | |
sum := 0.0 | |
for j := range n.values[0] { | |
for k := range m.values[0] { | |
sum += m.values[ig][k] * n.values[k][j] | |
} | |
retMat.values[ig][j] = sum | |
} | |
}(i) | |
} | |
wg.Wait() | |
return retMat | |
} | |
func (m Matrix) String() string { | |
var retString bytes.Buffer | |
for i := range m.values { | |
if i == 0 { | |
retString.WriteString("[ ") | |
} else { | |
retString.WriteString(" ") | |
} | |
for j := range m.values[i] { | |
retString.WriteString(strconv.FormatFloat(m.values[i][j], 'f', 2, 64)) | |
if j != len(m.values[i])-1 { | |
retString.WriteString(", ") | |
} | |
} | |
if i == len(m.values)-1 { | |
retString.WriteString(" ]") | |
} | |
retString.WriteString("\n") | |
} | |
return retString.String() | |
} | |
func main() { | |
mat1 := Eye(4) | |
mat2 := Eye(4) | |
fmt.Printf("%v", mat1.multiply(mat2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment