You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现:一维矩阵位置转二维矩阵(x,y)坐标

Converting 1D Array Position to 2D Matrix Coordinates (ROW×COL)

Great question! Let's break this down with clear, generalizable rules—since the core logic depends on how the 2D matrix was flattened into a 1D array (most often row-first, which matches your 10×10 example).

Key Assumptions First

First, let's clarify two common indexing conventions (critical for getting the right coordinates):

  • 0-based indexing: Used in almost all programming languages (e.g., Python, C, Java), where the first element is at position 0.
  • 1-based indexing: Used in math, spreadsheets, or some legacy systems, where the first element is at position 1.

Case 1: Row-Major (Row-First) Order (Most Common)

This is the flattening method your 10×10 example uses: we store all elements of row 0 first, then row 1, and so on until the last row.

For 0-Based Indexing

Given:

  • ROW: Number of rows in the original 2D matrix
  • COL: Number of columns in the original 2D matrix
  • pos: Position in the 1D array (starts at 0)

The 2D coordinates (x, y) (where x = row index, y = column index) are:

x = pos // COL  # Integer division (discard remainder)
y = pos % COL   # Modulo operation (get remainder)

Example: 11×12 Matrix (0-Based)

If pos = 25:

  • x = 25 // 12 = 2 (3rd row, since we start counting at 0)
  • y = 25 % 12 = 1 (2nd column)
    Corresponding 2D coordinate: (2, 1)

For 1-Based Indexing

If your 1D position starts at 1, adjust first to 0-based, then convert back:

pos_0 = pos - 1
x = (pos_0 // COL) + 1
y = (pos_0 % COL) + 1

Example: 11×12 Matrix (1-Based)

If pos = 25:

  • pos_0 = 24
  • x = (24 // 12) + 1 = 2 + 1 = 3
  • y = (24 % 12) + 1 = 0 + 1 = 1
    Corresponding 2D coordinate: (3, 1)

Case 2: Column-Major (Column-First) Order

Less common in general programming, but used in languages like Fortran or some linear algebra libraries. Here, we store all elements of column 0 first, then column 1, etc.

For 0-Based Indexing

x = pos % ROW
y = pos // ROW

For 1-Based Indexing

pos_0 = pos - 1
x = (pos_0 % ROW) + 1
y = (pos_0 // ROW) + 1

Verify Your 10×10 Example

Your 10×10 solution (x = pos / 10, y = pos % 10) aligns perfectly with row-major 0-based indexing—since integer division of pos by 10 (the number of columns) gives the row index, and modulo 10 gives the column index.

内容的提问来源于stack exchange,提问作者Huy Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:32:52