我在使用GO从文本文件中用矩阵填充2D数组时遇到问题。
我遇到的主要问题是创建一个2D数组,因为我必须计算数组的维数,GO似乎不接受数组维度中的VAR:
nb_lines = number of line of the array
nb_col = number of columns of the array
// read matrix from file
whole_file,_ := ioutil.ReadFile("test2.txt")
// get each line of the file in tab_whole_file
tab_whole_file := strings.Split(string(whole_file), "\n")
// first line of the table
tab_first_line := strings.Split(tab_whole_file[0], "\t")
nb_col := len(tab_first_line)
nb_lines := len(tab_whole_file) - 1
// at this point I tried to build a array to contain the matrix values from the texte file
var columns [nb_lines][nb_col]float64 // does not work
columns := make([][]float64, nb_lines, nb_col) // does not work
columns := make([nb_lines][nb_col]float64) // does not work
columns := [nb_lines][nb_col]float64{} // does not work
columns := [][]float64{} // panic: runtime error: index out of range
for i := 0; i < nb_lines ; i++ { // for each line of the table from text file
line := strings.Split(tab_whole_file[0], "\t") // split one line to get each table values
for j := 1; j < len(line) ; j++ {
columns[i][j], _ = strconv.ParseFloat(line[j], 64) // assign each value to the table columns[i][j]
}
}
答案 0 :(得分:1)
Go中float64
的矩阵声明为[][]float64
var matrix [][]float64
您可以使用:=
运算符初始化矩阵并自动声明类型
matrix := [][]float64{}
请注意,上面这一行不是一个简单的声明,是用于创建新空片的语法
// creates an empty slice of ints
x := []int{}
// creates a slice of ints
x := []int{1, 2, 3, 4}
使用[]float64{}
将定义和分配结合在一起。请注意,以下两行是不同的
// creates a slice of 4 ints
x := []int{1, 2, 3, 4}
// creates an array of 4 ints
x := [4]int{1, 2, 3, 4}
切片可以调整大小,数组具有固定大小。
回到您的问题,here's an example,演示如何创建float64
矩阵并在矩阵中添加新行。
package main
import "fmt"
func main() {
matrix := [][]float64{}
matrix = append(matrix, []float64{1.0, 2.0, 3.0})
matrix = append(matrix, []float64{1.1, 2.1, 3.1})
fmt.Println(matrix)
}
您可以从此示例开始并更新您的脚本。
答案 1 :(得分:1)
例如,
package main
import (
"bytes"
"fmt"
"io/ioutil"
"strconv"
)
func loadMatrix(filename string) ([][]float64, error) {
var m [][]float64
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
rows := bytes.Split(data, []byte{'\n'})
for r := len(rows) - 1; r >= 0; r-- {
if len(rows[r]) != 0 {
break
}
rows = rows[:len(rows)-1]
}
m = make([][]float64, len(rows))
nCols := 0
for r, row := range rows {
cols := bytes.Split(row, []byte{'\t'})
if r == 0 {
nCols = len(cols)
}
m[r] = make([]float64, nCols)
for c, col := range cols {
if c < nCols && len(col) > 0 {
e, err := strconv.ParseFloat(string(col), 64)
if err != nil {
return nil, err
}
m[r][c] = e
}
}
}
return m, nil
}
func main() {
filename := "matrix.tsv"
m, err := loadMatrix(filename)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Matrix:")
fmt.Println(m)
fmt.Println("\nBy [row,column]:")
for r := range m {
for c := range m[0] {
fmt.Printf("[%d,%d] %5v ", r, c, m[r][c])
}
fmt.Println()
}
fmt.Println("\nBy [column,row]:")
for c := range m[0] {
for r := range m {
fmt.Printf("[%d,%d] %5v ", c, r, m[r][c])
}
fmt.Println()
}
}
输出:
$ cat matrix.tsv
3.14 1.59 2.7 1.8
42
$ go run matrix.go
Matrix:
[[3.14 1.59 2.7 1.8] [42 0 0 0]]
By [row,column]:
[0,0] 3.14 [0,1] 1.59 [0,2] 2.7 [0,3] 1.8
[1,0] 42 [1,1] 0 [1,2] 0 [1,3] 0
By [column,row]:
[0,0] 3.14 [0,1] 42
[1,0] 1.59 [1,1] 0
[2,0] 2.7 [2,1] 0
[3,0] 1.8 [3,1] 0
$
答案 2 :(得分:0)
我对我的程序进行了一些修改,这几乎是&#34;几乎&#34;工作示例...不是很优雅;)矩阵中仍然存在问题:矩阵的第1列对应于文件的第1行,因此我无法访问列:(
func main() {
matrix := [][]float64{} // matrix corresponding to the text file
// Open the file.
whole_file,_ := ioutil.ReadFile("test2.tsv")
// mesasure the size of the table
tab_whole_file := strings.Split(string(whole_file), "\n")
tab_first_line := strings.Split(tab_whole_file[0], "\t")
nb_col := len(tab_first_line)
nb_lines := len(tab_whole_file) - 1
// I dont know why this number is longer than I expected so I have to substract 1
for i := 0; i < nb_lines ; i++ {
numbers := []float64{} // temp array
line := strings.Split(tab_whole_file[i], "\t")
for j := 1; j < nb_col ; j++ { // 1 instead of 0 because I dont want the first column of row names and I cant store it in a float array
if nb, err := strconv.ParseFloat(line[j], 64); err == nil {
numbers = append(numbers,nb) // not very elegant/efficient temporary array
}
}
matrix = append(matrix, numbers)
}
}