Vector computations

A column vector is an m x 1 matrix, also known as the transpose of a row vector. A matrix transposition is when a matrix is flipped over its diagonal, often denoted with a superscript T. We can see an example of a column vector in the following image:

If we want to implement a column vector in Go, we can use the Gonum vector package to initialize this vector, as shown in the following code block:

package main

import (
"fmt"
"gonum.org/v1/gonum/mat"
)
func main() {
v := mat.NewVecDense(4, []float64{0, 1, 2, 3})
matPrint(v)
}

func matrixPrint(m mat.Matrix) {
formattedMatrix := mat.Formatted(m, mat.Prefix(""), mat.Squeeze())
fmt.Printf("%v ", formattedMatrix)
}

This will print out a column vector like the one shown in the preceding image.

We can also do some neat vector manipulation with the Gonum package. For example, in the following code block, we can see how simple it is to double the values within a vector. We can add two vectors together using the AddVec function, thus creating a doubled vector. We also have the prettyPrintMatrix convenience function to make our matrix easier to read:

package main

import (
"fmt"
"gonum.org/v1/gonum/mat"
)

func main() {
v := mat.NewVecDense(5, []float64{1, 2, 3, 4, 5})
d := mat.NewVecDense(5, nil)
d.AddVec(v, v)
fmt.Println(d)
}

func prettyPrintMatrix(m mat.Matrix) {
formattedM := mat.Formatted(m, mat.Prefix(""), mat.Squeeze())
fmt.Printf("%v ", formattedM)
}

The result of this function, that is, a doubled vector, is as follows:

The gonum/mat package also gives us many other neat helper functions for vectors, including the following:

  • Cap() gives you the capacity of the vector
  • Len() gives you the number of columns within the vector
  • IsZero() validates whether or not a vector is zero-sized
  • MulVec() multiplies vectors a and b and serves the result
  • AtVec() returns the value within the vector at a given position

The vector manipulation functions within the gonum/mat package help us to easily manipulate vectors into the datasets that we need.

Now that we are done with vectors, let's look at matrices.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.135.80