Golang : Create matrix with Gonum Matrix package example
Here is an example of how to create and display matrix properly in Golang with Gonum package. Nothing special in this tutorial, will write another tutorial on how to find the matrix determinants and performing matrix calculations later on.
Here you go!
package main
import (
"fmt"
"github.com/gonum/matrix/mat64"
)
func main() {
m := mat64.NewDense(3, 5, nil)
// fill in m with some elements
for i := 0; i < 3; i++ {
m.Set(i, i, 99)
}
// wrong way to print matrix
fmt.Println("m : ", m)
// proper way
// refer to https://godoc.org/github.com/gonum/matrix/mat64#Excerpt
fmt.Printf("m :\n%v\n\n", mat64.Formatted(m, mat64.Prefix(" "), mat64.Excerpt(2)))
// print all m elements
fmt.Printf("m :\n%v\n\n", mat64.Formatted(m, mat64.Prefix(""), mat64.Excerpt(0)))
data := []float64{1, 2, 3}
m2 := mat64.NewDense(3, 1, data)
// print all m2 elements
fmt.Printf("m2 :\n%v\n\n", mat64.Formatted(m2, mat64.Prefix(""), mat64.Excerpt(0)))
// to build this matrix
// ⎡1 2 3⎤
// ⎢4 5 6⎥
// ⎣7 8 9⎦
// use SetRow or SetCol
m3 := mat64.NewDense(3, 3, nil)
m3.SetRow(0, data)
data2 := []float64{4, 5, 6}
m3.SetRow(1, data2)
data3 := []float64{7, 8, 9}
m3.SetRow(2, data3)
// print all m3 elements
fmt.Printf("m3 :\n%v\n\n", mat64.Formatted(m3, mat64.Prefix(""), mat64.Excerpt(0)))
// get transpose with m3.T()
fmt.Printf("m3 transpose :\n%v\n\n", mat64.Formatted(m3.T(), mat64.Prefix(""), mat64.Excerpt(0)))
}
Output:
m : &{{3 5 5 [99 0 0 0 0 0 99 0 0 0 0 0 99 0 0]} 3 5}
m :
Dims(3, 5)
⎡99 0 ... ... 0 0⎤
⎢ 0 99 0 0⎥
⎣ 0 0 ... ... 0 0⎦
m :
⎡99 0 0 0 0⎤
⎢ 0 99 0 0 0⎥
⎣ 0 0 99 0 0⎦
m2 :
⎡1⎤
⎢2⎥
⎣3⎦
m3 :
⎡1 2 3⎤
⎢4 5 6⎥
⎣7 8 9⎦
m3 transpose :
⎡1 4 7⎤
⎢2 5 8⎥
⎣3 6 9⎦
References:
https://godoc.org/github.com/gonum/matrix/mat64#Dense.SetRow
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+16.3k Golang : File path independent of Operating System
+12.9k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+8k Golang : Metaprogramming example of wrapping a function
+8k Golang : Qt splash screen with delay example
+20.9k Golang : How to force compile or remove object files first before rebuild?
+11.1k Use systeminfo to find out installed Windows Hotfix(s) or updates
+10.9k Golang : Fix - does not implement sort.Interface (missing Len method)
+5k Golang : Issue HTTP commands to server and port example
+6.1k Golang : How to get capacity of a slice or array?
+11.4k Golang : Fuzzy string search or approximate string matching example
+15.7k Golang : Read large file with bufio.Scanner cause token too long error
+17.4k Golang : Defer function inside init()