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
+9k Golang : Write multiple lines or divide string into multiple lines
+18.4k Golang : Set, Get and List environment variables
+8.4k Golang : Convert(cast) []byte to io.Reader type
+15.7k Golang : Update database with GORM example
+17.4k Golang : Parse date string and convert to dd-mm-yyyy format
+20.5k Golang : Convert date string to variants of time.Time type examples
+8.6k Golang : Gaussian blur on image and camera video feed examples
+25.2k Golang : Daemonizing a simple web server process example
+16.1k Golang : Find out mime type from bytes in buffer
+27.4k PHP : Count number of JSON items/objects
+9.9k Golang : Check a web page existence with HEAD request example
+9.6k Golang : ffmpeg with os/exec.Command() returns non-zero status