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
+16.2k Golang : Delete files by extension
+20.5k Golang : Convert PNG transparent background image to JPG or JPEG image
+11.5k Golang : GTK Input dialog box examples
+38.8k Golang : How to read CSV file
+9.9k Golang : Get login name from environment and prompt for password
+10.6k Golang : Get UDP client IP address and differentiate clients by port number
+9.2k Golang : Changing a RGBA image number of channels with OpenCV
+13.7k Golang : convert rune to unicode hexadecimal value and back to rune character
+7.2k Golang : Rot13 and Rot5 algorithms example
+17.9k Golang : Get command line arguments
+21.5k Golang : Use TLS version 1.2 and enforce server security configuration over client
+10.7k Golang : Sieve of Eratosthenes algorithm