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
+11.1k Golang : Concatenate (combine) buffer data example
+16.3k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+9.5k Golang : Turn string or text file into slice example
+5.2k Golang : fmt.Println prints out empty data from struct
+20.8k Golang : Sort and reverse sort a slice of strings
+21k Curl usage examples with Golang
+5.5k Unix/Linux : How to test user agents blocked successfully ?
+9.8k Golang : Identifying Golang HTTP client request
+10.7k Golang : Replace a parameter's value inside a configuration file example
+11.2k Golang : Generate DSA private, public key and PEM files example
+5.1k Javascript : Shuffle or randomize array example
+20.1k Android Studio : AlertDialog and EditText to get user string input example