patternjavaMinor
How is the formula for calculation in row/column major obtained?
Viewed 0 times
calculationthemajorobtainedcolumnforhowrowformula
Problem
In my book, this formula is given for calculation of address of row major order's element $[I,J]$:
Address of $[I,J]$th element in row major order $= B + W[n(I-L_r)+ [J-L_c]]$
where B denotes base address, W denotes element size in bytes, n is the number of columns; $L_r$ is the first row number, $L_c$ is the first column number.
A similar formula is given for address in column major order.
I would like to know how this formula is obtained.
Address of $[I,J]$th element in row major order $= B + W[n(I-L_r)+ [J-L_c]]$
where B denotes base address, W denotes element size in bytes, n is the number of columns; $L_r$ is the first row number, $L_c$ is the first column number.
A similar formula is given for address in column major order.
I would like to know how this formula is obtained.
Solution
Row-major order stores the rows of the array one after another in memory. That is, the array
is stored as
To determine the address of an element in this list, we need to know how many elements come before it. For element $[I,J]$, this is the number of complete rows above row $I$ times the length of a row, which is $(I-L_r)\times n$, plus the number of elements before it in the current row, which is $J-L_c$.
Since the first element is at address $B$ and each element takes $W$ bytes, the addresses of the elements are $B$, $B+W$, $B+2W$, ... and, in general, if there are $k$ elements before you, your address is $B+kW$. For element $[I,J]$, we have calculated that $k=n(I-L_r)+(J-L_c)$.
For column-major, the argument is basically the same. If you understand the above, it should be easy to adapt it.
a d g j
b e h k
c f i lis stored as
a d g j b e h k c f i lTo determine the address of an element in this list, we need to know how many elements come before it. For element $[I,J]$, this is the number of complete rows above row $I$ times the length of a row, which is $(I-L_r)\times n$, plus the number of elements before it in the current row, which is $J-L_c$.
Since the first element is at address $B$ and each element takes $W$ bytes, the addresses of the elements are $B$, $B+W$, $B+2W$, ... and, in general, if there are $k$ elements before you, your address is $B+kW$. For element $[I,J]$, we have calculated that $k=n(I-L_r)+(J-L_c)$.
For column-major, the argument is basically the same. If you understand the above, it should be easy to adapt it.
Code Snippets
a d g j
b e h k
c f i la d g j b e h k c f i lContext
StackExchange Computer Science Q#96852, answer score: 5
Revisions (0)
No revisions yet.