代码之家  ›  专栏  ›  技术社区  ›  Ecanyte

矩阵索引/展平

  •  1
  • Ecanyte  · 技术社区  · 1 年前

    我得到了一个带有维度的矩阵 dim = nxmx4 。我想把这个矩阵展平为一个新的一维长度矩阵 l = n*m*4 使用3个嵌套for循环。

    for (let x = 0; x < n; x++) {
        for (let y = 0; y < m; y++) {
            for (let i = 0; i < 4; i++) {
                let index = ?;
                newMatrix[index] = matrix[x][y][i];
            }
        }
    }
    

    此外,条件 index % 4 == i 应该始终保持不变。

    更准确地说,矩阵[x][y][i]的值目前并不重要(可以是任意的),只要每次迭代索引增加一个。 对于i=0->索引=0,4,8。。。应该返回|i=1->索引=1,5,9,…|i=2->索引=2,6,10,…|并且i=3->索引=3,7,11。。。

    我现在想不出正确的索引。提前谢谢。

    1 回复  |  直到 1 年前
        1
  •  1
  •   user24714692    1 年前

    您可以使用 index = x * m * 4 + y * 4 + i; :

    let newMatrix = [];
    for (let x = 0; x < n; x++) {
      for (let y = 0; y < m; y++) {
        for (let i = 0; i < 4; i++) {
          let index = x * m * 4 + y * 4 + i;
          newMatrix[index] = matrix[x][y][i];
        }
      }
    }
    
        2
  •  0
  •   jsejcksn    1 年前

    您需要对每次循环迭代的总偏移量求和。以下是一个基于问题中代码的可复制示例,其中包含解释逻辑的参数化变量和注释:

    /** @type {number[][][]} */
    const matrix = [
      [
        [1,  2,  3,  4],
        [5,  6,  7,  8],
        [9, 10, 11, 12],
      ],
      [
        [13, 14, 15, 16],
        [17, 18, 19, 20],
        [21, 22, 23, 24],
      ],
    ];
    
    /** @type {number[]} */
    const flat = [];
    
    const a = matrix.length; // 2
    const b = matrix[0].length; // 3
    const c = matrix[0][0].length; // 4
    
    for (let ia = 0; ia < a; ia++) {
      for (let ib = 0; ib < b; ib++) {
        for (let ic = 0; ic < c; ic++) {
          const index =
              ic // offset from inner loop
            + (c * ib) // offset from middle loop
            + (c * b * ia); // offset from outer loop
          flat[index] = matrix[ia][ib][ic];
        }
      }
    }
    
    console.log(flat); // [1, 2, … 23, 24]