Generating Symmetric Matrices in Numpy

numpy create diagonal matrix
symmetric matrix
scipy triangular matrix
numpy random matrix
numpy diagonal matrix of ones
implementation of symmetric matrix
numpy set diagonal of a matrix
set diagonal of matrix to zero numpy

I am trying to generate symmetric matrices in numpy. Specifically, these matrices are to have random places entries, and in each entry the contents can be random. Along the main diagonal we are not concerned with what enties are in there, so I have randomized those as well.

The approach I have taken is to first generate a nxn all zero matrix and simply loop over the indices of the matrices. However, given considering looping is relatively expensive in python, I'm wondering if I can acheive the same thing without using python's for loops.

Is there some things built into numpy that allow me to acheive my goal more efficiently?

Here is my current code:

import numpy as np
import random

def empty(x, y):
    return x*0

b = np.fromfunction(empty, (n, n), dtype = int)

for i in range(0, n):
    for j in range(0, n):
        if i == j:
            b[i][j] = random.randrange(-2000, 2000)
            switch = random.random()
            if switch > random.random():
                a = random.randrange(-2000, 2000)
                b[i][j] = a
                b[j][i] = a
                b[i][j] = 0
                b[j][i] = 0

You could just do something like:

import numpy as np

N = 100
b = np.random.random_integers(-2000,2000,size=(N,N))
b_symm = (b + b.T)/2

Where you can choose from whatever distribution you want in the np.random or equivalent scipy module.

Update: If you are trying to build graph-like structures, definitely check out the networkx package:

which has a number of built-in routines to build graphs:

Also if you want to add some number of randomly placed zeros, you can always generate a random set of indices and replace the values with zero.

numpy.tril - Numpy and Scipy, I need to make a matrix (in the form of a numpy array) by taking a list of parameters of length N and returning an array of dimensions N+1 x N+1 where the  Defining Matrix using Numpy; Transpose Matrix; Here, we will learn how to create a symmetric matrix using a non-symmetric matrix? The following equation shows how a dot product of Matrix A and A T can result in a symmetric matrix. S = A.A T. Python code creating symmetric matrix

I'd better do:

a = np.random.rand(N, N)
m = np.tril(a) + np.tril(a, -1).T

because in this case all elements of a matrix are from same distribution (uniform in this case).

Create symmetrical matrix from list of values, When creating a symmetric matrix, array. array() is used as the underlying storage. To create the numpy matrix, numpy. zeros() is called. When creating a symmetric matrix, array.array() is used as the underlying storage. To create the numpy matrix, numpy.zeros() is called. The elements in both matrices are 64b integers.

There is a mathematical property in matrices that allows such structure to be created easily: A.T * A where A is a row vector and A.t is the transpose (a column vector). This always returns a square positive definite symmetric matrix which is always invertible, so you have no worries with null pivots ;)

# any matrix algebra will do it, numpy is simpler
import numpy.matlib as mt

# create a row vector of given size
size  = 3
A = mt.rand(1,size)

# create a symmetric matrix size * size
symmA = A.T * A

Implementing a Symmetric Matrix in Python, A complex- or real-valued matrix whose eigenvalues will be computed. Returns eigenvalues of real symmetric or complex Hermitian (conjugate symmetric) arrays. eigh from numpy import linalg as LA >>> x = np.random.random() >>> Q  First, you will create a matrix containing constants of each of the variable x,y,x or the left side. Then the matrix for the right side. left_hand_side = np.matrix ( [ [1,1,-1], # x + y − z = 4 [1,-2,3], # x − 2y + 3z = −6 [2,3,1]]) # 2x + 3y + z = 7 left_hand_side.

If you don't mind having zeros on the diagonal you could use the following snippet:

def random_symmetric_matrix(n):
    _R = np.random.uniform(-1,1,n*(n-1)/2)
    P = np.zeros((n,n))
    P[np.triu_indices(n, 1)] = _R
    P[np.tril_indices(n, -1)] = P.T[np.tril_indices(n, -1)]
    return P

Note that you only need to generate n*(n-1)/2 random variables due to the symmetry.

numpy.linalg.eigvals, rank, determinant, trace, etc. of an array. eigen values of matrices; matrix and vector of a complex Hermitian (conjugate symmetric) or a real symmetric matrix​. from numpy import linalg as geek # Creating an array using array # function a​  Generating Symmetric Matrices in Numpy (3) I'd better do: a = np.random.rand(N, N) m = np.tril(a) + np.tril(a, -1).T. because in this case all elements of a matrix are from same distribution (uniform in this case).

I'm using the following function to make a matrix symmetric both vertically and horizontally:

def make_sym(a):
    w, h = a.shape
    a[w - w // 2 :, :] = np.flipud(a[:w // 2, :])
    a[:, h - h // 2:] = np.fliplr(a[:, :h // 2])

Let check how it works:

>>> m = (np.random.rand(10, 10) * 10).astype(
>>> make_sym(m)
>>> m
array([[2, 7, 5, 7, 7, 7, 7, 5, 7, 2],
       [6, 3, 9, 3, 6, 6, 3, 9, 3, 6],
       [1, 4, 6, 7, 2, 2, 7, 6, 4, 1],
       [9, 2, 7, 0, 8, 8, 0, 7, 2, 9],
       [5, 5, 6, 1, 9, 9, 1, 6, 5, 5],
       [5, 5, 6, 1, 9, 9, 1, 6, 5, 5],
       [9, 2, 7, 0, 8, 8, 0, 7, 2, 9],
       [1, 4, 6, 7, 2, 2, 7, 6, 4, 1],
       [6, 3, 9, 3, 6, 6, 3, 9, 3, 6],
       [2, 7, 5, 7, 7, 7, 7, 5, 7, 2]])

Numpy, numpy.linalg.eigh(a, UPLO='L')[source]¶. Return the eigenvalues and eigenvectors of a Hermitian or symmetric matrix. Returns two objects, a 1-D array​  You can treat lists of a list (nested list) as matrix in Python. However, there is a better way of working Python matrices using NumPy package. NumPy is a package for scientific computing which has support for a powerful N-dimensional array object.

numpy.linalg.eigh, The eigenvalues of a symmetric matrix are always real and the Let's verify these facts with some random matrices: We will create these following random matrix using the NumPy library. Matrix with floating values; Random Matrix with Integer values; Random Matrix with a specific range of numbers; Matrix with desired size ( User can choose the number of rows and columns of the matrix ) Create Matrix of Random Numbers in Python. We will create each and every

Eigenvalues and Eigenvectors - Mathematical Python, scikit-learn: machine learning in Python. Generate a random symmetric, positive-definite matrix. Read more in the User Guide. Parameters. n_dimint. D = [2 0 0 0 0 4 0 0 0 0 3 0 0 0 0 1] In this matrix, v is the following vector: v = [2 4 3 1] The Numpy function diag () can be used to create square diagonal matrices: v = np.array( [2, 4, 3, 1]) np.diag(v) array ( [ [2, 0, 0, 0], [0, 4, 0, 0], [0, 0, 3, 0], [0, 0, 0, 1]])

sklearn.datasets.make_spd_matrix, The objects are all the same type into a NumPy arrays structure. • The package offers a A NUMPY MATRIX. Creation on the fly, generation of a sequence, loading from a file print(s). #eigenvalues and eigenvectors of a symmetric matrix. Generate a sparse matrix of the given shape and density with randomly distributed values. Parameters m, n int. shape of the matrix. density real, optional. density of the generated matrix: density equal to one means a full matrix, density of 0 means a matrix with no non-zero items. format str, optional. sparse matrix format. dtype dtype, optional