Skip to main content

Matrices

A matrix is an interesting topic. Memory is just one dimensional. It helps to see how multi dimensional matrices live in memory.

The core data structure is the array. When you declare a matrix, nested arrays represent it.

array and matrix used interchangeably

Keep in mind that matrices and arrays mean the same thing here. They're the same. Programming languages also use arrays to build matrices.

how arrays are used to represent matrices
  • A one dimensional matrix is a plain array. Its values are primitives.
  • A two dimensional matrix is an array of arrays. Its values are pointers to the inner arrays.
  • A three dimensional matrix is array of array of arrays.

You can nest this to any depth.

matrix-stored-as-arrays
finding size of matrices

To find the size of a matrix in each dimension, you must know its structure in terms of the inner arrays.

Mental model for multi dimensional matrices

Learn how 1D and 2D matrices live in memory. The rest just nest more layers on top. Whatever the size, the real data sits in a 1-D matrix. That's just an array. And an array is a continuous block of memory holding primitive values.

N dimensional matrix mental model

An N dimensional array is an array whose elements are N-1 arrays. This repeats until the elements are primitive types.

For a 3D matrix, picture a cube of many layers. Each layer is a 2D array.

For a 2D matrix, picture a flat plank of many small blocks. Each block is a 1D array.

int[][][] A = {
{ // A[0] (first level)
{ 1, 2, 3, 4 }, // A[0][0] (second level)
{ 5, 6, 7, 8 }, // A[0][1]
{ 9, 10, 11, 12 } // A[0][2]
},
{ // A[1]
{ 13, 14, 15, 16 }, // A[1][0]
{ 17, 18, 19, 20 }, // A[1][1]
{ 21, 22, 23, 24 } // A[1][2]
}
};

int[][][][] A = {
{ // A[0] (first level)
{ // A[0][0] (second level)
{ 1, 2 }, // A[0][0][0] (third level)
{ 3, 4 }, // A[0][0][1]
{ 5, 6 } // A[0][0][2]
},
{ // A[0][1]
{ 7, 8 }, // A[0][1][0]
{ 9, 10 }, // A[0][1][1]
{ 11, 12 } // A[0][1][2]
}
},
{ // A[1]
{ // A[1][0]
{ 13, 14 },
{ 15, 16 },
{ 17, 18 }
},
{ // A[1][1]
{ 19, 20 },
{ 21, 22 },
{ 23, 24 }
}
}
};