Fred
Fred

Reputation: 697

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

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), "\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]
    }
}

Upvotes: 1

Views: 1933

Answers (3)

peterSO
peterSO

Reputation: 166598

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{'\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()
    }
}

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  
$

Upvotes: 1

Fred
Fred

Reputation: 697

I did few modifications to my program and this is a "almost" working example... not very elegant ;) There is still a problem in the matrix : the 1st column of the matrix correspond to the 1st line of the file so I dont have access to columns :(

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

Upvotes: 0

Simone Carletti
Simone Carletti

Reputation: 176412

A matrix of float64 in Go is declared as [][]float64

var matrix [][]float64

You can use the := operator to initialize the matrix and declare the type automatically

matrix := [][]float64{}

Note that this the line above is not a simple declaration, is the syntax used to create a new empty slice

// creates an empty slice of ints
x := []int{} 
// creates a slice of ints
x := []int{1, 2, 3, 4} 

The use of []float64{} combines together the definition and the allocation. Note that the following two lines are different

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

Slices can be resized, arrays have fixed size.

Back to your problem, here's an example that demonstrates how to create a matrix of float64 and append new rows to the matrix.

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

You can start from this example and update your script.

Upvotes: 1

Related Questions