GO:如何分配 2 x 2 可变大小数组中的所有元素?

我在使用 GO 用文本文件中的矩阵填充二维数组时遇到问题。


我的主要问题是创建一个二维数组,因为我必须计算数组的维度,而 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]

    }

}


沧海一幻觉
浏览 141回答 3
3回答

猛跑小猪

例如,package mainimport (&nbsp; &nbsp; "bytes"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "io/ioutil"&nbsp; &nbsp; "strconv")func loadMatrix(filename string) ([][]float64, error) {&nbsp; &nbsp; var m [][]float64&nbsp; &nbsp; data, err := ioutil.ReadFile(filename)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil, err&nbsp; &nbsp; }&nbsp; &nbsp; rows := bytes.Split(data, []byte{'\n'})&nbsp; &nbsp; for r := len(rows) - 1; r >= 0; r-- {&nbsp; &nbsp; &nbsp; &nbsp; if len(rows[r]) != 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; rows = rows[:len(rows)-1]&nbsp; &nbsp; }&nbsp; &nbsp; m = make([][]float64, len(rows))&nbsp; &nbsp; nCols := 0&nbsp; &nbsp; for r, row := range rows {&nbsp; &nbsp; &nbsp; &nbsp; cols := bytes.Split(row, []byte{'\t'})&nbsp; &nbsp; &nbsp; &nbsp; if r == 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nCols = len(cols)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; m[r] = make([]float64, nCols)&nbsp; &nbsp; &nbsp; &nbsp; for c, col := range cols {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if c < nCols && len(col) > 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e, err := strconv.ParseFloat(string(col), 64)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return nil, err&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m[r][c] = e&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return m, nil}func main() {&nbsp; &nbsp; filename := "matrix.tsv"&nbsp; &nbsp; m, err := loadMatrix(filename)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(err)&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println("Matrix:")&nbsp; &nbsp; fmt.Println(m)&nbsp; &nbsp; fmt.Println("\nBy [row,column]:")&nbsp; &nbsp; for r := range m {&nbsp; &nbsp; &nbsp; &nbsp; for c := range m[0] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("[%d,%d] %5v&nbsp; ", r, c, m[r][c])&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println()&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println("\nBy [column,row]:")&nbsp; &nbsp; for c := range m[0] {&nbsp; &nbsp; &nbsp; &nbsp; for r := range m {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("[%d,%d] %5v&nbsp; ", c, r, m[r][c])&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println()&nbsp; &nbsp; }}输出:$ cat matrix.tsv3.14&nbsp; &nbsp; 1.59&nbsp; &nbsp; 2.7 1.842$ go run matrix.goMatrix:[[3.14 1.59 2.7 1.8] [42 0 0 0]]By [row,column]:[0,0]&nbsp; 3.14&nbsp; [0,1]&nbsp; 1.59&nbsp; [0,2]&nbsp; &nbsp;2.7&nbsp; [0,3]&nbsp; &nbsp;1.8&nbsp;&nbsp;[1,0]&nbsp; &nbsp; 42&nbsp; [1,1]&nbsp; &nbsp; &nbsp;0&nbsp; [1,2]&nbsp; &nbsp; &nbsp;0&nbsp; [1,3]&nbsp; &nbsp; &nbsp;0&nbsp;&nbsp;By [column,row]:[0,0]&nbsp; 3.14&nbsp; [0,1]&nbsp; &nbsp; 42&nbsp;&nbsp;[1,0]&nbsp; 1.59&nbsp; [1,1]&nbsp; &nbsp; &nbsp;0&nbsp;&nbsp;[2,0]&nbsp; &nbsp;2.7&nbsp; [2,1]&nbsp; &nbsp; &nbsp;0&nbsp;&nbsp;[3,0]&nbsp; &nbsp;1.8&nbsp; [3,1]&nbsp; &nbsp; &nbsp;0&nbsp;&nbsp;$

慕田峪4524236

float64Go中的矩阵被声明为[][]float64var matrix [][]float64您可以使用:=运算符来初始化矩阵并自动声明类型matrix := [][]float64{}请注意,上面这行不是简单的声明,而是用于创建新的空切片的语法// creates an empty slice of intsx := []int{}&nbsp;// creates a slice of intsx := []int{1, 2, 3, 4}&nbsp;的使用[]float64{}结合了定义和分配。注意下面两行是不同的// creates a slice of 4 intsx := []int{1, 2, 3, 4}&nbsp;// creates an array of 4 intsx := [4]int{1, 2, 3, 4}&nbsp;切片可以调整大小,数组具有固定大小。回到你的问题,这是一个演示如何创建矩阵float64并将新行附加到矩阵的示例。package mainimport "fmt"func main() {&nbsp; &nbsp; matrix := [][]float64{}&nbsp; &nbsp; matrix = append(matrix, []float64{1.0, 2.0, 3.0})&nbsp; &nbsp; matrix = append(matrix, []float64{1.1, 2.1, 3.1})&nbsp; &nbsp; fmt.Println(matrix)}您可以从此示例开始并更新您的脚本。

回首忆惘然

我对我的程序做了很少的修改,这是一个“几乎”的工作示例......不是很优雅;)矩阵中仍然存在一个问题:矩阵的第一列对应于文件的第一行,所以我不可以访问列:(func main() {&nbsp; &nbsp; matrix := [][]float64{} // matrix corresponding to the text file&nbsp; &nbsp; // Open the file.&nbsp; &nbsp; whole_file,_ := ioutil.ReadFile("test2.tsv")&nbsp; &nbsp; // mesasure the size of the table&nbsp; &nbsp; tab_whole_file := strings.Split(string(whole_file), "\n")&nbsp; &nbsp; tab_first_line := strings.Split(tab_whole_file[0], "\t")&nbsp; &nbsp; nb_col := len(tab_first_line)&nbsp; &nbsp; nb_lines := len(tab_whole_file) - 1&nbsp;// I dont know why this number is longer than I expected so I have to substract 1&nbsp; &nbsp; for i := 0; i < nb_lines ; i++ {&nbsp; &nbsp; &nbsp; numbers := []float64{} // temp array&nbsp; &nbsp; &nbsp; line := strings.Split(tab_whole_file[i], "\t")&nbsp; &nbsp; &nbsp; 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&nbsp; &nbsp; &nbsp; &nbsp; if nb, err := strconv.ParseFloat(line[j], 64); err == nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; numbers = append(numbers,nb) // not very elegant/efficient temporary array&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; matrix = append(matrix, numbers)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go