Skip to main content

array-row-major-index

array-row-major-index Function

Syntax:

array-row-major-index array &rest subscripts → index

Arguments and Values:

array—an array.

subscripts—a list of valid array indices for the array.

index—a valid array row-major index for the array.

Description:

Computes the position according to the row-major ordering of array for the element that is specified by subscripts, and returns the offset of the element in the computed position from the beginning of array.

For a one-dimensional array, the result of array-row-major-index equals subscript. array-row-major-index ignores fill pointers.

Examples:

(setq a (make-array(4 7) :element-type(unsigned-byte 8))) 
(array-row-major-index a 1 2)9
(array-row-major-index
(make-array(2 3 4)
:element-type(unsigned-byte 8)
:displaced-to a
:displaced-index-offset 4)
0 2 1)9

Notes:

A possible definition of array-row-major-index, with no error-checking, is

(defun array-row-major-index (a &rest subscripts)

(apply #’+ (maplist #’(lambda (x y)

(* (car x) (apply #’* (cdr y))))

subscripts

(array-dimensions a))))

Expanded Reference: array-row-major-index

Basic Usage

array-row-major-index converts multi-dimensional subscripts into a single row-major index. This is the position the element would occupy if the array were flattened into a one-dimensional sequence in row-major order.

;; For a 1D array, the row-major index equals the subscript
(array-row-major-index (make-array 5) 3)
=> 3

;; For a 3x4 array: index = row * num_cols + col
(array-row-major-index (make-array '(3 4)) 1 2)
=> 6

(array-row-major-index (make-array '(3 4)) 2 3)
=> 11

3D Arrays

For a 3D array with dimensions (d0, d1, d2), the row-major index of element (i, j, k) is i * d1 * d2 + j * d2 + k.

(array-row-major-index (make-array '(2 3 4)) 1 2 3)
=> 23

(array-row-major-index (make-array '(2 3 4)) 0 0 0)
=> 0

Use with row-major-aref

array-row-major-index and row-major-aref work together to access elements by their flattened position.

(let ((m (make-array '(2 3) :initial-contents '((a b c) (d e f)))))
(let ((idx (array-row-major-index m 1 1)))
(list idx (row-major-aref m idx))))
=> (4 E)

Iterating Over All Elements

Combined with array-total-size and row-major-aref, this provides a way to iterate over all elements of any array regardless of its rank.

(let ((m (make-array '(2 3) :initial-contents '((1 2 3) (4 5 6))))
(sum 0))
(dotimes (i (array-total-size m) sum)
(incf sum (row-major-aref m i))))
=> 21