我的向量是874!元素,我想将其变成一个三角形矩阵(即正方形矩阵的右上角)。
输入示例:
1
2
3
4
5
6
7
8
9
10
示例输出:
1 2 4 7
3 5 8
6 9
10
空白可能会填充NA。我希望矩阵是否在这种情况下。
我不知道您不想使用哪种编程语言,也不知道您希望将数字存储在哪个顺序中。
您应该考虑具有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以正确的顺序用is值填充方阵(res)。现在,您可以轻松完成目标矩阵的维数转换。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句