transform the upper/lower triangular part of a symmetric matrix (2D array) into a 1D array and return it to the 2D format

Related searches

In this question it is explained how to access the lower and upper triagular parts of a given matrix, say:

m = np.matrix([[11, 12, 13],
               [21, 22, 23],
               [31, 32, 33]])

Here I need to transform the matrix in a 1D array, which can be done doing:

indices = np.triu_indices_from(m)
a = np.asarray( m[indices] )[-1]
#array([11, 12, 13, 22, 23, 33])

After doing a lot of calculations with a, changing its values, it will be used to fill a symmetric 2D array:

new = np.zeros(m.shape)
for i,j in enumerate(zip(*indices)):
    new[j]=a[i]
    new[j[1],j[0]]=a[i]

Returning:

array([[ 11.,  12.,  13.],
       [ 12.,  22.,  23.],
       [ 13.,  23.,  33.]])

Is there a better way to accomplish this? More especifically, avoiding the Python loop to rebuild the 2D array?

The fastest and smartest way to put back a vector into a 2D symmetric array is to do this:


Case 1: No offset (k=0) i.e. upper triangle part includes the diagonal

import numpy as np

X = np.array([[1,2,3],[4,5,6],[7,8,9]])
#array([[1, 2, 3],
#       [4, 5, 6],
#       [7, 8, 9]])

#get the upper triangular part of this matrix
v = X[np.triu_indices(X.shape[0], k = 0)]
print(v)
# [1 2 3 5 6 9]

# put it back into a 2D symmetric array
size_X = 3
X = np.zeros((size_X,size_X))
X[np.triu_indices(X.shape[0], k = 0)] = v
X = X + X.T - np.diag(np.diag(X))
#array([[1., 2., 3.],
#       [2., 5., 6.],
#       [3., 6., 9.]])

The above will work fine even if instead of numpy.array you use numpy.matrix.


Case 2: With offset (k=1) i.e. upper triangle part does NOT include the diagonal

import numpy as np

X = np.array([[1,2,3],[4,5,6],[7,8,9]])
#array([[1, 2, 3],
#       [4, 5, 6],
#       [7, 8, 9]])

#get the upper triangular part of this matrix
v = X[np.triu_indices(X.shape[0], k = 1)] # offset
print(v)
# [2 3 6]

# put it back into a 2D symmetric array
size_X = 3
X = np.zeros((size_X,size_X))
X[np.triu_indices(X.shape[0], k = 1)] = v
X = X + X.T
#array([[0., 2., 3.],
#       [2., 0., 6.],
#       [3., 6., 0.]])

Program to print Lower triangular and Upper triangular matrix of an , Prerequisite – Multidimensional Arrays in C / C++ Lower triangular matrix is a matrix which contain elements below principle diagonal including Function to form cout << "Upper triangular matrix: \n" ;. upper(matrix, row, col);. return 0;. } Minimum number of steps to convert a given matrix into Upper Hessenberg matrix� transform the upper/lower triangular part of a symmetric matrix (2D array) into a 1D array and return it to the 2D format Ask Question Asked 6 years, 11 months ago

Do you just want to form a symmetric array? You can skip the diagonal indices completely.

m=np.array(m)
inds = np.triu_indices_from(m,k=1)
m[(inds[1], inds[0])] = m[inds]

m

array([[11, 12, 13],
       [12, 22, 23],
       [13, 23, 33]])

Creating a symmetric array from a:

new = np.zeros((3,3))
vals = np.array([11, 12, 13, 22, 23, 33])
inds = np.triu_indices_from(new)
new[inds] = vals
new[(inds[1], inds[0])] = vals
new
array([[ 11.,  12.,  13.],
       [ 12.,  22.,  23.],
       [ 13.,  23.,  33.]])

Program to check if matrix is upper triangular, Print lower triangular matrix pattern from given array � C Program To Check whether Matrix is Skew Symmetric or not � Program for triangular patterns of alphabets� transform the upper/lower triangular part of a symmetric matrix (2D array) into a 1D array and return it to the 2D format indices = np.triu_indices_from(A) A = np.asarray(A[indices]) Fuente Compartir

You can use Array Creation Routines such as numpy.triu, numpy.tril, and numpy.diag to create a symmetric matrix from a triangular. Here's a simple 3x3 example.

a = np.array([[1,2,3],[4,5,6],[7,8,9]])
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

a_triu = np.triu(a, k=0)
array([[1, 2, 3],
       [0, 5, 6],
       [0, 0, 9]])

a_tril = np.tril(a, k=0)
array([[1, 0, 0],
       [4, 5, 0],
       [7, 8, 9]])

a_diag = np.diag(np.diag(a))
array([[1, 0, 0],
       [0, 5, 0],
       [0, 0, 9]])

Add the transpose and subtract the diagonal:

a_sym_triu = a_triu + a_triu.T - a_diag
array([[1, 2, 3],
       [2, 5, 6],
       [3, 6, 9]])

a_sym_tril = a_tril + a_tril.T - a_diag
array([[1, 4, 7],
       [4, 5, 8],
       [7, 8, 9]])

numpy.triu_indices — NumPy v1.19 Manual, Return the indices for the upper-triangle of an (n, m) array. similar function, for lower-triangular. Compute two different sets of indices to access 4x4 arrays, one for the upper triangular part starting at the main diagonal, and one starting two� [X,Y] = meshgrid(x,y) returns 2-D grid coordinates based on the coordinates contained in vectors x and y. X is a matrix where each row is a copy of x, and Y is a matrix where each column is a copy of y.

Javanotes 8.1, Section 7.5 -- Two-dimensional Arrays, The elements of a 2D array are arranged in rows and columns, and the new Each row, in turn, is a list of values separated by commas and enclosed between braces Those one-dimensional arrays are the rows of the 2D array. public class SymmetricMatrix { private double[][] matrix; // A triangular matrix to hold the data� def get_close_markers(markers,centroids=None, min_distance=20): if centroids is None: centroids = [m['centroid']for m in markers] centroids = np.array(centroids) ti = np.triu_indices(centroids.shape[0], 1) def full_idx(i): #get the pair from condensed matrix index #defindend inline because ti changes every time return np.array([ti[0][i], ti[1][i]]) #calculate pairwise distance, return dense

[PDF] MATLAB array manipulation tips and tricks, efficient ways of performing low-level array manipulation in MATLAB. Document Format) version was created from the PS file with ps2pdf, a part of 10.1 Multiply each 2D slice with the same matrix (element-by-element) . Extract upper triangular part. not change the number of elements in an array. Storing a symmetric matrix requires only the upper triangular part, including the diagonal, since the remaining elements can be reconstructed from the former ones. To indicate the use of this mode of matrix storage to client software, the value of the metadata attribute storage-mode must be set to "symmetric-upper" (see Metadata ).

An icon used to represent a menu that can be toggled by interacting with this icon.

Comments
  • I have to process the middle term array a before returning to the symmetric 2D-array
  • You can manipulate m[indup] as long as it returns a 1D numpy array in the correct order. Is there a particular issue with this?
  • a have to come from array([11, 12, 13, 22, 23, 33]) to a corresponding 2D-array array([[11,12,13],[12,22,23],[13,23,33]])
  • Do you mean you want a symmetric array from a?
  • Works only for 3x3 and smaller
  • Thanks for the tip ;)
  • I executed same steps but a turns out to be array([[ 22., 12., 13.], [ 12., 44., 23.], [ 13., 23., 66.]]) Diagonal elements are added to themselves
  • @Madhav, numpy may have updated np.tril and np.triu since this post to include diagonals when k=0. Or my original response may have just been wrong. I've corrected it by subtracting the diagonal with np.diag.