dpjo15650 2016-03-13 12:07
浏览 30
已采纳

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

I'm having problems filling a 2D array with a matrix from a text file using GO.

The main problem I have is to create a 2D array because I have to calculate the dimension of the array and GO does not seem to accept VAR in array dimension :

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), "
")
// 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]
    }
}
  • 写回答

3条回答 默认 最新

  • dongni3854 2016-03-13 19:02
    关注

    For example,

    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{'
    '})
        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("
    By [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("
    By [column,row]:")
        for c := range m[0] {
            for r := range m {
                fmt.Printf("[%d,%d] %5v  ", c, r, m[r][c])
            }
            fmt.Println()
        }
    }
    

    Output:

    $ 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条)

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)