如何将三角矩阵索引转换为行,列坐标? [英] How to convert triangular matrix indexes in to row, column coordinates?

查看:232
本文介绍了如何将三角矩阵索引转换为行,列坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些索引:

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,etc...

哪个是矩阵中节点的索引(包括对角线元素):

Which are indexes of nodes in a matrix (including diagonal elements):

1
2  3
4  5  6
7  8  9  10
11 12 13 14 15
16 17 18 19 20 21
etc...

,我需要从这些索引中获取i,j坐标:

and I need to get i,j coordinates from these indexes:

1,1
2,1 2,2
3,1 3,2 3,3
4,1 4,2 4,3 4,4
5,1 5,2 5,3 5,4 5,5
6,1 6,2 6,3 6,4 6,5 6,6
etc...

当我需要计算坐标时,我只有一个索引,而无法访问其他索引.

When I need to calculate coordinates I have only one index and cannot access others.

推荐答案

根本没有优化:

int j = idx;
int i = 1;

while(j > i) {
    j -= i++;
}

已优化:

int i = std::ceil(std::sqrt(2 * idx + 0.25) - 0.5);
int j = idx - (i-1) * i / 2;

这是演示:

您正在寻找这样的我:

sumRange(1, i-1) < idx && idx <= sumRange(1, i)

当sumRange(min,max)对介于min和max之间的整数求和时,都包括在内. 但既然您知道:

when sumRange(min, max) sum integers between min and max, both inxluded. But since you know that :

sumRange(1, i) = i * (i + 1) / 2

那么您就有了:

idx <= i * (i+1) / 2
=> 2 * idx <= i * (i+1)
=> 2 * idx <= i² + i + 1/4 - 1/4
=> 2 * idx + 1/4 <= (i + 1/2)²
=> sqrt(2 * idx + 1/4) - 1/2 <= i

这篇关于如何将三角矩阵索引转换为行,列坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆