如何将矩阵的索引映射到一维数组(C ++)?

时间:2012-12-23 23:35:40

标签: c++ c arrays matrix

我有一个8x8矩阵,如下所示:

char matrix[8][8];

另外,我有一个包含64个元素的数组,如下所示:

char array[64];

然后我将矩阵绘制成一个表格,并用数字填充单元格,每个数字从左到右,从上到下递增。

如果我有索引3(列)和4(行)到矩阵中,我知道它对应于数组中第35位的元素,因为我可以在表格中看到画。我相信有一些公式可以将矩阵的2个索引转换为数组的单个索引,但我无法弄清楚它是什么。

有什么想法吗?

3 个答案:

答案 0 :(得分:78)

大多数语言存储多维数组的方式是进行如下转换:

如果matrix有大小,则n乘以m [即我从0到(n-1),j从0到(m-1)],然后:

matrix[ i ][ j ] = array[ i*m + j ]

所以它就像一个基数'n'的数字系统。请注意,最后一个维度的大小无关紧要。


为了概念性理解,可以考虑一个(3x5)矩阵,其中'i'作为行号,'j'作为列号。如果您从i,j = (0,0) --> 0开始编号。对于'row-major'排序(如下所示),布局如下:

           |-------- 5 ---------|
  Row      ______________________   _ _
   0      |0    1    2    3    4 |   |
   1      |5    6    7    8    9 |   3
   2      |10   11   12   13   14|  _|_
          |______________________|
Column     0    1    2    3    4 

当您沿着行移动(即增加列数)时,您只是开始向上计数,因此数组索引为0,1,2...。当你到达第二行时,你已经有5个条目,所以你从索引1*5 + 0,1,2...开始。在第三行,您已经有2*5个条目,因此索引为2*5 + 0,1,2...

对于更高维度,这个想法概括,即对于3D matrix L由N乘以M:

matrix[ i ][ j ][ k ] = array[ i*(N*M) + j*M + k ]

等等。


要获得非常好的解释,请参阅:http://www.cplusplus.com/doc/tutorial/arrays/;或者更多技术方面:http://en.wikipedia.org/wiki/Row-major_order

答案 1 :(得分:10)

对于行主要排序,我认为声明matrix[ i ][ j ] = array[ i*n + j ]是错误的。

偏移量应为offset = (row * NUMCOLS) + column

您的陈述结果为row * NUMROWS + column,这是错误的。

您提供的链接会给出正确的解释。

答案 2 :(得分:5)

这样的东西?

//columns = amount of columns, x = column, y = row
var calculateIndex = function(columns, x, y){
    return y * columns + x;
};

以下示例将索引转换回x和y坐标。

//i = index, x = amount of columns, y = amount of rows
var calculateCoordinates = function(index, columns, rows){
    //for each row
    for(var i=0; i<rows; i++){
        //check if the index parameter is in the row
        if(index < (columns * i) + columns && index >= columns * i){
            //return x, y
            return [index - columns * i, i];
        }
    }
    return null;
};