简体   繁体   中英

numpy/scipy: fill upper triangle of array with elements of 1d vector?

Say I have a flattened 1D vector that exactly corresponds to the upper triangle elements of a 2D array.

The 1D vector needs to be read into the upper triangle.

I might do the following in python:

triu_flat = ...
row,col = np.triu_indices(50)

D = np.zeros((50,50))

i=0 
for r in row: 
    for c in col:
        D[r,c] = triu_flat[i]
        i++

However, there must be a way to do this via numpy/scipy operations.

You can simply use the indices returned by triu_indices() , no need for a for loop:

import numpy

data = numpy.arange(6)
out = numpy.zeros((3, 3))
inds = numpy.triu_indices(len(out))
out[inds] = data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM