Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- # Deepcopy is imported in order not to change the matrix a itself
- from copy import deepcopy
- def sparse_gen(num_row, num_col, spar):
- # Total number of elements
- nelem = num_row * num_col
- # Number of nonzero elements
- n_nonzero = int(nelem * spar)
- # Position of nonzero elements
- poselem = random.sample(range(nelem), n_nonzero)
- # Create an empty dictionary here
- spardict = {};
- # Add entries into the dictionary here in a for loop
- for i in range(len(poselem)):
- # Create a string from the number in poselem and use it as a key
- key = str(poselem[i])
- # Select -1 or 1 randomly
- spardict[key] = random.choice([-1,1])
- # Add the size of the matrix with the key value -1
- spardict['-1'] = [num_row, num_col]
- # Return the sparse matrix for reference later on
- return spardict
- # Here is the function for addition of two matrices
- def sparse_add(a, b):
- # First lets check if the matrix sizes are equal or not
- if a['-1'] != b['-1'] :
- print('Matrix sizes should be equal. Exiting!')
- return
- # Copy matrix a into matrix c the sum a + b = c
- c = deepcopy(a)
- # Delete the size info from b and retrieve the keys
- del b['-1']
- bkeys = b.keys()
- # Write the for loop for summation iterating over keys of b
- for bkey in iter(bkeys):
- if (bkey in a):
- if ((c[bkey] + b[bkey]) == 0):
- del c[bkey]
- continue
- else:
- c[bkey] += b[bkey]
- else:
- c[bkey] = b[bkey]
- # Since it gives rise to problems later readd b['-1']
- b['-1'] = a['-1']
- return c
- # The function for printing sparse matrices is defined here
- def sparse_print(a):
- # Lets retrieve the size information first (rows, columns)
- # Remember the size information is a list
- nrow = a['-1'][0]
- ncol = a['-1'][1]
- # Lets write a for loop to print out the relevant info
- for i in range(nrow * ncol):
- # if the i is in a print that value otherwise print 0
- return_str = ""
- if str(i) in a:
- return_str += "%3d " % a[str(i)]
- else:
- return_str += "%3d " % 0
- # Print new line if we hit the end of the row
- if ((i + 1) % nrow) == 0:
- return_str += "\n"
- return_str += "\n\n"# Two new line characters to avoid confusion
- return return_str
- # The function for converting sparse matrices to full is defined here
- def mat2sparse(a):
- spardict = {}
- num_row = len(a)
- num_col = len(a[0])
- nelem = num_row * num_col
- # Input the size information
- spardict['-1'] = [num_row, num_col]
- for i in range(num_row):
- for j in range(num_col):
- if a[i][j] != 0:
- # Calculate the position of the key
- key = str(i*num_col + j)
- spardict[key] = a[i][j]
- return spardict
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement