如何将矩阵的索引映射到一维数组(c++)
How to map the indexes of a matrix to a 1-dimensional array (C++)?
我有一个8x8的矩阵,像这样:
char matrix[8][8];
同样,我有一个64个元素的数组,像这样:
char array[64];
然后我将矩阵绘制为表格,并用数字填充单元格,每个数字从左到右,从上到下递增。
如果我在矩阵中有索引3(列)和4(行),我知道它对应于数组中位置35的元素,正如我所绘制的表中所看到的那样。我相信有某种公式可以将矩阵的2个索引转换为数组的单个索引,但我不知道它是什么。
任何想法?
大多数语言存储多维数组的方式是进行如下转换:
如果matrix
的大小为n(行)× m(列),并且我们使用"行为主排序";(先按行数计算)然后:
matrix[ i ][ j ] = array[ i*m + j ]
.
这里i从0到(n-1) j从0到(m-1)
它就像一个以m为底的数制。注意,最后一个维度的大小(这里是行数)无关紧要。
从概念上理解,考虑一个(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
对于行主排序,我认为matrix[ i ][ j ] = array[ i*n + j ]
语句是错误的。
偏移量应为offset = (row * NUMCOLS) + column
。
你的语句结果是row * NUMROWS + column
,这是错误的。
您提供的链接给出了正确的解释
像这样?
//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;
};
- 将二维数组的所有元素插入到一维数组中
- C++语法差异:二维和一维数组(指针算术)
- 将一维数组写入 CSV C++中的不同列?
- C++:将矩阵存储在一维数组中
- 如何在一维数组中的每个元素中都有多个int值
- 以C++填充一维数组
- 用于在一维数组上嵌套循环操作的正确 openmp 指令
- 如何在 <threads> c++ 中使用和一维数组进行矩阵乘法?
- C++按内存地址将多维数组更改为一维数组
- 在 c++ 中返回一维数组时出错
- 一维数组映射方式的性能差异问题
- 如何使用一维数组更改二维数组中的值?
- 使用二维数组作为一维数组是否正确?可能会导致未定义的行为左右?
- 将一维数组转换为二维数组
- 如何使用一维数组列表初始化二维数组
- 在一维数组中对二维进行排序
- 将一维数组的索引转换为二维数组
- 通过访问二维数组实现双线性插值的概念类似于一维数组
- 将二维数组传递到只需要一维数组的函数中(C++)
- 如何访问带有多个括号的一维数组以提高可读性