Skip to content

Vectors vs. matrices

mikera edited this page Apr 4, 2013 · 10 revisions

Introduction

core.matrix supports both vectors (1D arrays) and matrices (2D arrays). This page explains the differences between the two.

Matrix properties

  • Can be though of as a 2D nested array e.g.: 1 2 3] [4 5 6] [7 8 9
  • Always have dimensionality 2 - equivalent to a 2D array
  • Are indexed by [row column]
  • Can be transposed, which reverses rows and columns
  • Support some matrix-only operations, e.g. det, trace
  • A slice of a Matrix is a 1D vector

Vector properties

  • Can be though of as a 1D array e.g.: [1 2 3]
  • Always have dimensionality 1 - equivalent to a 1D array
  • Are indexed by [position]
  • Transposing a vector is the identity function: if you call transpose on a vector, you will get the same vector back unchanged
  • Supports some vector-only operations, e.g. distance, dot-product
  • A slice of a vector is a 0D scalar

Why have both?

Technically, you can always emulate vectors by using matrices: either using a Nx1 column matrix or a 1xN row matrix. Indeed, some mathematics systems (like Matlab) expect you to do just this.

However there are some important reason that we need to have both:

  • core.matrix is designed to be a general purpose N-Dimensional API, so it needs to support both the 1D and 2D cases in general.
  • Many underlying matrix implementations have both vectors and matrices so we need to support them
  • It can catch some runtime type errors (e.g. passing a matrix where a vector is required)
  • In some cases, using vectors rather than matrices offers higher performance (due to a simpler data structure and less complex indexing)

Which should I use?

Usually this will be clear from what is needed for your problem: if you need a 2D array of numbers then you should be using a matrix. If you need a 1D array of numbers then you should use a vector.

Further discussion / reading: