Fer VT
Fer VT

Reputation: 508

Golang - How to remove a row from a matrix?

So I have this 2D slice, for example:

s := [][]int{
    {0, 1, 2, 3},
    {4, 5, 6, 7},
    {8, 9, 10, 11},
}

fmt.Println(s)

//Outputs: [[0 1 2 3] [4 5 6 7] [8 9 10 11]]

How can I remove a full row from this 2D slice, so that the result would look like this if I decide to remove the middle row:

[[0 1 2 3] [8 9 10 11]]

Upvotes: 1

Views: 1525

Answers (2)

Zippo
Zippo

Reputation: 16420

The formula to delete row at index i is:

s = append(s[:i], s[i+1:])

Here's a working example:

package main

import (
    "fmt"
)

func main() {
    s := [][]int{
        {0, 1, 2, 3},
        {4, 5, 6, 7}, // This will be removed.
        {8, 9, 10, 11},
    }

    // Delete row at index 1 without modifying original slice by
    // appending to a new slice.
    s2 := append([][]int{}, append(s[:1], s[2:]...)...)
    fmt.Println(s2)

    // Delete row at index 1. Original slice is modified.
    s = append(s[:1], s[2:]...)
    fmt.Println(s)
}

Try it in the Go playground.

I recommend you to read Go Slice Tricks. Some of the tricks can be applied to multidimensional slices as well.

Upvotes: 3

Md Johirul Islam
Md Johirul Islam

Reputation: 5162

You can try the following:

i := 1
s = append(s[:i],s[i+1:]...)

You can try the working code in the Golang playground

Another alternative way is to use the following:

i := 1
s = s[:i+copy(s[i:], s[i+1:])]

Golang Playground

Upvotes: 2

Related Questions