Mapping 2D Array to 1D Array¶
Consider a 2D array:
[
[00, 01, 02],
[11, 12, 13]
]
To convert this 2D array to a 1D array using row-major order, you list the elements row by row:
[ 00 ,01 , 02, 11, 12 , 13 ]
0 1 2 3 4 5
Row Major Order¶
For example, the element 12
is at position (1, 2)
(row index 1, column index 2). Its corresponding index in the 1D array is 4
.
The general formula for mapping a 2D array element at position \((\text{row_index},\ \text{col_index})\) to a 1D array index is:
Explanation:
- \(\text{row_index} \times \text{number_of_cols}\): Counts all elements in the rows before the current row.
- \(\text{col_index}\): Gives the position within the current row.
So, to find the 1D index, count all elements in previous rows, then add the column index of the current element.
Column Major Order¶
To convert a 2D array to a 1D array using column-major order, you list the elements column by column:
[ 00, 11, 01, 12, 02, 13]
0 1 2 3 4 5
For example, the element 12
is at position (1, 2)
(row index 1, column index 2). Its corresponding index in the 1D array is 3
.
The general formula for mapping a 2D array element at position \((\text{row_index},\ \text{col_index})\) to a 1D array index in column-major order is:
Explanation:
- \(\text{col_index} \times \text{number_of_rows}\): Counts all elements in the columns before the current column.
- \(\text{row_index}\): Gives the position within the current column.
So, to find the 1D index, count all elements in previous columns, then add the row index of the current element.