【问题标题】:Convert vector into a triangular matrix将向量转换为三角矩阵
【发布时间】:2016-02-01 18:50:12
【问题描述】:

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

示例输入:

1
2
3
4
5
6
7
8
9
10

示例输出:

1 2 4 7
  3 5 8
    6 9
      10

空白可以用 NA 填充。如果矩阵是这种方式,我会更喜欢。

【问题讨论】:

  • 同一行/列的连续元素之间的差异是否必然增加?
  • 我已经通过更好地计算方阵尺寸来编辑我的答案

标签: vector matrix


【解决方案1】:

我不知道您想使用哪种编程语言,我也不知道您希望以哪种顺序存储您的号码。

您应该考虑拥有 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)。一旦你现在你的目标矩阵尺寸,这可以很容易地完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 2017-06-10
    • 2011-03-27
    • 2020-01-30
    • 1970-01-01
    相关资源
    最近更新 更多