Matrices can be created using tables, too. For instance, a matrix of zeros with dimensions N by M can be created with the following code:
N=3;M=4
mt = {} // create the empty table
for i=1,N do
mt[i] = {} // create a new row
for j=1,M do
mt[i][j] = 0
end
end
In this case, indexing is done with double indices, for example, mt[2][2]. This represents the entry at the second row and second column. Each row above is a table, so you have a table array of tables. Unlike the matrix data type, you cannot use single indexing (linear indexing) to access any of the table entries. See Indexing for more information.
You can build a matrix as an array by composing the two indices into a single one. This allows for linear indexing to access elements.
N=3;M=4
mt = {} // create the empty matrix
for i=1,N do
for j=1,M do
mt[i*M + j] = 0
end
end
Tables allocate space only for non-empty entries. That is, a table creation such as the following only allocates enough memory to store one single element:
> t = {}
> t[10] = 1 // Only one item at location 10
> print(t[1]) // The rest are all nil & takes no memory
nil
The implication is that for sparse matrices, this can save memory and allows you to index the elements in natural way. So, for example, a 3x3 diagonal matrix with entries of 1 can be created as follows:
mt = {} // create the empty matrix
for i=1,3 do
mt[i] = {} // create a new row
mt[i][i] = 1 // diagonal entries only
end
The above allocates memory for the diagonal elements only.