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

GO : how to Assign all elements in 2 by 2 array of variable size?

我在使用 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]
    }
}

float64的矩阵在Go中声明为[][]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)
}

您可以从此示例开始并更新您的脚本。

我对我的程序做了一些修改,这是一个 "almost" 工作示例...不是很优雅 ;) 矩阵中仍然存在问题:矩阵的第一列对应于第一列文件的行,所以我无权访问列:(

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)
    }
}

例如,

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  
$