Using Matrices in Go(lang)

In this post I’ll describe how to get started using gonum/matrix package for using matrices for math and stats applications. (Documentation here.) I’ll begin with a bit about setting up the Go environment drawn from the How to Write Code page on the Go website. (I highly recommend reading this if you’re unfamiliar with Go.) Next I’ll provide a commented usage case.

Setting Up the Environment

I am using Ubuntu 14.04 LTS, I have not tried any of this on Windows or Mac. I’ll assume you’ve installed Go from here. To make life easier, I edited/created some system variables:

  1. I added the location of my go binaries to my $PATH variable. This will let me use the go commands from the command line.
  2. I created a variable $GOPATH for the directory where I will write my go code. This tells the go binaries where to install packages from github.

To effect these changes, I edited the .bashrc file in my home directory. Here are the lines I added at the bottom:

# add variables for Go
export PATH=$PATH:/usr/local/go/bin
export GOPATH=$HOME/go

Now that these variables have been defined, I installed two packages from Dan Kortschack’s gonum repository on github. From the command line, I executed the following commands:

go get github.com/gonum/matrix
go get github.com/gonum/blas

This utilizes the variables we added to the .bashrc file. If this doesn’t work, go back to the How to Write Code page. I then created a directory matex for my matrix example and started writing a program matex.go.

mkdir go/src/github.com/cjohnson318/matex
cd go/src/github.com/cohnson318/matex
vim matex.go

Code

Here is a listing of the code in matex.go. First I import mat64 from the gonum\matrix package. In the main block I create three matrices x, y, and z using the NewDense() function. I put data into the first two matrices x and y. Then perform the addition computation using the Add() method of z, passing the matrices x and y as arguments. Finally, as a sanity check, I print out the values of z using the At() method of z.

package main

import(
  "fmt"
  "github.com/gonum/matrix/mat64"
)

func main() {

    // initialize a 3 element float64 slice
    dx := make( []float64, 3 )

    // set the elements
    dx[0] = 2
    dx[1] = 2
    dx[2] = 3

    // pass the slice dx as data to the matrix x
    x := mat64.NewDense( 3, 1, dx )

    // alternatively, create the matrix y by
    // inserting the data directly as an argument
    y := mat64.NewDense( 3, 1, []float64{1, 4, 5})

    // create an empty matrix for the addition
    z := mat64.NewDense( 3, 1, []float64{0, 0, 0})

    // perform the addition
    z.Add( x, y )

    // print the output
    fmt.Printf( "%f %f %f\n", z.At(0,0), z.At(1,0), z.At(2,0) )
}

Leave a Reply

Your email address will not be published. Required fields are marked *