1d array from 2d array

I need to extract a column from a 2d array into a 1d array.
I tried search the internet but not successful.
Can someone please help?
Thanks

Do you have a slice of rows or a slice of columns?

If it is a slice of colums, you can just do foo[n]. If it is a slice of rows, you need to use a loop and build a resulting slice with the individual column.

thanks for your quick reply.
following is the info.

input : x [ ][ ] float64 {{1,2,3},{4,5,6},{7,8,9}}
desired output y [ ] float64 eg: [2,5,8]

package main

import "log"

func main() {
  var input = [][]float64{{1,2,3},{4,5,6},{7,8,9}}
  var result = []float64{}
 
  for _, arr := range input {
    for _, item := range arr {
      result = append(result, item)
    }
  }

  log.Println(result)
}

This gets you all the values in a single slice, going back to Nobbz’s answer. If you want help with this, its done like this:

package main

import "log"

func main() {
  var input = [][]float64{{1,2,3},{4,5,6},{7,8,9}}
  var row = 1

  var result = []float64{}
  for _, column := range input {
    result = append(result, column[row])
  }

  log.Println(result)
}
package main

import "fmt"

func column(x [][]float64, col int) []float64 {
	y := make([]float64, 0, len(x))
	for _, row := range x {
		if col < 0 || col >= len(row) {
			return nil
		}
		y = append(y, row[col])
	}
	return y[0:len(y):len(y)]
}

func main() {
	x := [][]float64{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
	fmt.Println(x)
	y := column(x, 1)
	fmt.Println(y)
}

https://play.golang.org/p/oPxrsFvdr00

[[1 2 3] [4 5 6] [7 8 9]]
[2 5 8]
1 Like

thanks guys for your quick reply. it works. but I was thinking if I can take the transpose of the input and read the roll. Will that work?

The XY problem is asking about your attempted solution rather than your actual problem. Read The XY Problem.


If the actual problem is transposing a matrix:

package main

import "fmt"

func transpose(x [][]float64) [][]float64 {
	if len(x) == 0 {
		return [][]float64{}
	}
	rows, cols := len(x[0]), len(x)
	y := make([][]float64, rows)
	for c, xrow := range x {
		if len(xrow) != rows {
			return nil
		}
		if c >= cols {
			return nil
		}
		for r := range xrow {
			if r >= rows {
				return nil
			}
			if y[r] == nil {
				y[r] = make([]float64, cols)
			}
			y[r][c] = x[c][r]
		}
	}
	return y
}

func main() {
	tests := []struct {
		x [][]float64
	}{
		{[][]float64{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}},
		{[][]float64{{1, 2}}},
		{[][]float64{{1, 2}, {3, 4}}},
		{[][]float64{{1, 2}, {3, 4}, {5, 6}}},
	}
	for _, tt := range tests {
		x := tt.x
		fmt.Println("x", x)
		y := transpose(x)
		fmt.Println("y", y)
		fmt.Println()
	}
}

https://play.golang.org/p/Q6Vrul80tVX

x [[1 2 3] [4 5 6] [7 8 9]]
y [[1 4 7] [2 5 8] [3 6 9]]

x [[1 2]]
y [[1] [2]]

x [[1 2] [3 4]]
y [[1 3] [2 4]]

x [[1 2] [3 4] [5 6]]
y [[1 3 5] [2 4 6]]

Hi petrus
thanks for your advise and help.
very much appreciated.

1 Like