Golang : Emulate NumPy way of creating matrix example
Problem:
You are so used to NumPy way of creating matrix and you have difficult time in adapting to Gonum's method. Is there any function in Golang that can offer the similar way of how NumPy
create matrix from an input string? Such as :
>>> import numpy as np
>>> A = np.mat('[1 2;3 4]')
>>> A
matrix([[1, 2],
[3, 4]])
Solution:
Created this function as a quick and dirty way for my own use and probably useful for you as well. However, bear in mind that this is a primitive Golang function and does not perform error checking on the input string.
Here you go!
package main
import (
"fmt"
"github.com/gonum/matrix/mat64"
"strconv"
"strings"
)
// WARNING: this function does not perform error checking on input string
// You probably need to modify this function to perform sanity check on stuff such as:
// such as only 1 pair of [ ]
// all columns and rows have number or 0
// all rows are same size [pynum will throw "ValueError: Rows not the same size."]
func matrix(str string) *mat64.Dense {
// remove [ and ]
str = strings.Replace(str, "[", "", -1)
str = strings.Replace(str, "]", "", -1)
// calculate total number of rows
parts := strings.SplitN(str, ";", -1)
rows := len(parts)
// calculate total number of columns
colSlice := strings.Fields(parts[0])
columns := len(colSlice)
// replace all ; with space
str = strings.Replace(str, ";", " ", -1)
// convert str to slice
// taken from https://www.socketloop.com/tutorials/golang-convert-string-to-array-slice
elements := strings.Fields(str)
//fmt.Println("Rows : ", rows)
//fmt.Println("Columns : ", columns)
// populate data for the new matrix(Dense type)
data := make([]float64, rows*columns)
for i := range data {
floatValue, _ := strconv.ParseFloat(elements[i], 64)
data[i] = floatValue
}
M := mat64.NewDense(rows, columns, data)
return M
}
func main() {
str := "[1 2 3 4 5 6 7 8;9 10 11 12 13 14 15 16;8 7 6 5 4 3 2 1]"
m := matrix(str)
// print all m elements
fmt.Printf("m :\n%v\n\n", mat64.Formatted(m, mat64.Prefix(""), mat64.Excerpt(0)))
// does not check for non-float or integer
// will replace alphabet with 0
m1 := matrix("[1 x 3; 4 5 a]")
// print all m1 elements
fmt.Printf("m1 :\n%v\n\n", mat64.Formatted(m1, mat64.Prefix(""), mat64.Excerpt(0)))
m2 := matrix("[1.1 2 3.4;4 5 68.8]")
// print all m2 elements
fmt.Printf("m2 :\n%v\n\n", mat64.Formatted(m2, mat64.Prefix(""), mat64.Excerpt(0)))
}
Output:
m :
⎡ 1 2 3 4 5 6 7 8⎤
⎢ 9 10 11 12 13 14 15 16⎥
⎣ 8 7 6 5 4 3 2 1⎦
m1 :
⎡1 0 3⎤
⎣4 5 0⎦
m2 :
⎡ 1.1 2 3.4⎤
⎣ 4 5 68.8⎦
Happy coding!
References:
http://docs.scipy.org/doc/scipy/reference/tutorial/linalg.html
https://www.socketloop.com/tutorials/golang-extract-sub-strings
See also : Golang : Linear algebra and matrix calculation example
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
+7.9k Android Studio : Rating bar example
+7.9k Prevent Write failed: Broken pipe problem during ssh session with screen command
+13.7k Golang : Fix image: unknown format error
+7.9k Golang : Routes multiplexer routing example with regular expression control
+20.4k PHP : Convert(cast) int to double/float
+7.8k Golang : Multiplexer with net/http and map
+8.1k Golang : How to check if input string is a word?
+17.2k Golang : [json: cannot unmarshal object into Go value of type]
+7.2k Golang : Gorrila set route name and get the current route name
+9.8k Golang : Find and replace data in all files recursively
+5.8k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+5.3k PHP : Convert CSV to JSON with YQL example