简体   繁体   中英

How to convert dictionary of tuple coordinates keys to sparse matrix

I stored the non-zero values of a sparse matrix in a dictionary. How would I this into an actual matrix?

def sparse_matrix(density,order):
    import random
    matrix = {}
    for i in range(density):
        matrix[(random.randint(0,order-1),
        random.randint(0,order-1))] = 1
    return matrix

Option 1 : Instead of keeping values in list and later creating the matrix, you can directly create the matrix and update the values in it. Please note you can have less number of non zero values than "order" as randint can return same number again.

Sample code :

import random
import numpy as np
def sparse_matrix(density,order):
    #matrix = [ [0 for i in range(order)] for i in range(order)]
    matrix = np.zeros((order,order))
    for i in range(density):
        matrix[(random.randint(0,order-1))][random.randint(0,order-1)] = 1
    return matrix 

Output :

sparse_matrix(2,4)

array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 1.]])

Option 2

You can create the dictionary using your code and use that dictionary to update the value in matrix.

    def sparse_matrix(density,order):
        import random
        #matrix = [ [0 for i in range(order)] for i in range(order)]
        matrix = {}
        for i in range(density):
            matrix[(random.randint(0,order-1)),(random.randint(0,order-1))] = 1
        return matrix
   #matrix of size order*order
   final_matrix = np.zeros((4,4))

   for key, value in sparse_matrix(2,4).items() :
       final_matrix[key] = value

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