A multidimensional array stores values using two or more indices. Although it is written as a grid, matrix, or tensor, memory is still linear. The indexing formula maps each logical position to one physical offset.
You use it when data has natural row, column, plane, or tensor structure.
Problem
Given a two-dimensional array with rows and columns, support reading and writing an element at position where
and
Structure
In row-major layout, rows are stored one after another:
The linear offset for position is:
Algorithm
Read an element from a row-major two-dimensional array:
get(A, r, c, i, j):
if i < 0 or i >= r:
error "row index out of bounds"
if j < 0 or j >= c:
error "column index out of bounds"
offset = i * c + j
return A[offset]Write an element:
set(A, r, c, i, j, x):
if i < 0 or i >= r:
error "row index out of bounds"
if j < 0 or j >= c:
error "column index out of bounds"
offset = i * c + j
A[offset] = xExample
Let
Here and .
To read position :
The flat storage is:
| step | action | result |
|---|---|---|
| 1 | check row | |
| 2 | check column | |
| 3 | compute offset | |
| 4 | read flat index |
Return .
Correctness
Row-major layout stores each row contiguously. Every full row before row contributes elements, so those rows contribute positions. Column then adds more positions inside row . Therefore, the offset identifies exactly .
The bounds checks ensure that only valid row and column positions are accessed.
Complexity
| operation | time |
|---|---|
| get | |
| set | |
| scan all elements |
Space usage:
When to Use
Multidimensional arrays are appropriate when:
- data is naturally tabular or grid-shaped
- dimensions are known or change rarely
- fast indexed access is required
- row-wise or block-wise traversal is common
They are less suitable when the data is very sparse. In that case, use a sparse matrix or coordinate representation.
Implementation
class Matrix:
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
self.a = [None] * (rows * cols)
def index(self, i, j):
if i < 0 or i >= self.rows:
raise IndexError("row index out of bounds")
if j < 0 or j >= self.cols:
raise IndexError("column index out of bounds")
return i * self.cols + j
def get(self, i, j):
return self.a[self.index(i, j)]
def set(self, i, j, x):
self.a[self.index(i, j)] = xtype Matrix[T any] struct {
data []T
rows int
cols int
}
func NewMatrix[T any](rows, cols int) *Matrix[T] {
return &Matrix[T]{
data: make([]T, rows*cols),
rows: rows,
cols: cols,
}
}
func (m *Matrix[T]) index(i, j int) (int, bool) {
if i < 0 || i >= m.rows {
return 0, false
}
if j < 0 || j >= m.cols {
return 0, false
}
return i*m.cols + j, true
}
func (m *Matrix[T]) Get(i, j int) (T, bool) {
var zero T
k, ok := m.index(i, j)
if !ok {
return zero, false
}
return m.data[k], true
}
func (m *Matrix[T]) Set(i, j int, x T) bool {
k, ok := m.index(i, j)
if !ok {
return false
}
m.data[k] = x
return true
}