Python Forum
Method on instance changing its representation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Method on instance changing its representation
#1
Im asked to make a class SparseMatrix that takes in a numpy array and represent it in a specific format(in my case its CSR format). Then im asked to add a method to the class that changes the representation from CSR to another format(in my case to CSC, but in casd you wish to help you can choose any simple format you wish). So basicly i would like to be able to create an instance "a=SparseMatrix(array)" and the have a method "toCCS" so that "b=a.toCCS()" creates a new instance b having the same array but represented a different format. The problem is that i get alot of attribute errors and other whatever i try... any tips?

import numpy as np

class SparseMatrix:

	

	def __init__(self,matrix):
	
		self.intern_represent = 'CSR'
		self.matrix=np.asarray(matrix)

		
		
	@property
	def numofnonzero(self):
		return len(self.values)
		
	
	def __repr__(self):
		return (' A= '+ str(self.values) +
                '\nIA= ' + str(self.IA) +
                '\nJA= '+ str(self.JA))
                
	def change(self,i,j,new):
		self.matrix[i][j]=new
	@property	
	def values(self):
		return self.matrix[np.nonzero(self.matrix)]
	@property
	def IA (self):
		IAlist =[]
		IAlist.append (0)
		for i in range (1,np.shape(self.matrix)[0]+1):
			num=IAlist [i-1] + np.count_nonzero(self.matrix [i-1])
			IAlist.append(num)
		IAlist=np.asarray (IAlist)
		return IAlist
	@property
	def JA(self):
		return np.nonzero(self.matrix)[1]
		

	
	 
	def toCSC(self): 
		#Here i want to be able to create a new instance with the same array but changing
        #the properties values ,IA and JA so the __repr__ prints it out in the desired way
	
		
		
		
a=SparseMatrix([[0,1,0],[1,2,3]])
print(a)
Reply
#2
Have toCSR change the self.intern_represent to a CSC and return self. Also, have IA and JA function check if self.intern_represent is a 'CSR' or 'CSC'.

So when you type this:
a=SparseMatrix([[0,1,0],[1,2,3]])
print("CSR:")
print(a)
b = a.toCSC()
print("\nCSC:")
print(b)
print("\nb.matrix:")
print(b.matrix)
you get:
Output:
CSR: A= [1 1 2 3] IA= [0 1 4] JA= [1 0 1 2] CSC: A= [1 1 2 3] IA= [0 1 3 4] JA= [0 1 1 1] b.matrix: [[0 1 0] [1 2 3]]
When my code doesn't work I don't know why **think** and when my code works I don't know why **think**
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020