将矢量转换为三角矩阵

时间:2014-03-20 11:45:11

标签: vector matrix

我有一个874的向量!元素,我想变成一个三角形矩阵(即方阵的右上角)。

示例输入:

1
2
3
4
5
6
7
8
9
10

示例输出:

1 2 4 7
  3 5 8
    6 9
      10

空白可以填充NA。如果矩阵是这样的话,我更喜欢。

1 个答案:

答案 0 :(得分:0)

我不知道您想使用哪种编程语言我也不知道您希望将数字存储在哪个订单中。

您应该考虑使用 N 元素,如果要生成方形矩阵,则其尺寸( n 行和列)由下式给出:

N = (n*(n+1))/2

因此,Python中的第一种方法(您应该考虑输入向量是否具有x ^ 2/2元素)可能是:

from math import sqrt

x = range(1,25+1) # This is your input vector
N = len(x) 

#N = (n*(n+1))/2 # Number of elements being stored in a triangular matrix.
n = (-1.0+sqrt(1.0+8.0*N))/2.0 # Solve the equation given by the previous relation.
n = int(round(n)) # Making it integer...

while (n*(n+1))/2 < N: # ... losing precission so we should use the first n being able ...
    if (n*(n+1))/2 < N: # ... to store your vector is used.
        n += 1    

res = [[0]*n for i in xrange(n)] # Here, we create a n*n matrix filled with zeros.
x = x[::-1] #Reverse the input so it can be consumed using pop (O(1) each extraction)

for j in xrange(n): # Fill the empty matrix following the triangular pattern and using...
    if not x:
        break
    for i in xrange(j+1):
        if not x:
            break
        res[i][j] = x.pop() # The elements from your input vector.

for row in res: # Let's print the result!
    print(row)

这个想法是消耗 x 用正确的值填充方形矩阵( res )。一旦你现在的目标矩阵尺寸,这很容易做到。

相关问题