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.2k Golang : How to fix html/template : "somefile" is undefined error?
+7k Golang : Get Alexa ranking data example
+14k Javascript : Prompt confirmation before exit
+7.7k Golang : Load DSA public key from file example
+10.2k Golang : Wait and sync.WaitGroup example
+4k Detect if Google Analytics and Developer Media are loaded properly or not
+5.2k Python : Convert(cast) string to bytes example
+9k Golang : Serving HTTP and Websocket from different ports in a program example
+5.9k Golang : Extract unicode string from another unicode string example
+8.5k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+4.8k JQuery : Calling a function inside Jquery(document) block
+9.8k Golang : Turn string or text file into slice example