0

In function add i want to return l as matrix type. but i am able to return it only as list type. My Aim is make m3 as matrix type and direclty want to display m3 as matrix which i have created str.

try: import sys

class matrix: def __init__(self,a): self.file=a c=open(self.file,'r') self.list=c.readlines() self.row=len(self.list) self.col=len(self.list[1].split(" ")) c.close templist=[] i=0 j=0 self.elements=[] while i<self.row: while j<self.col: templist=self.list[i].split(" ") self.elements.append(templist[j]) j=j+1 j=0 i=i+1 #return elem def __str__(self): #print self.file #print self.list s='' for x in self.list: s=s+x return s def __add__(self,other): #print self.elements #print other.elements i=0 l=[] while i<len(self.elements): l.append(int(self.elements[i])+int(other.elements[i])) i=i+1 #l=matrix(l) #print type(l) return l def write(self,sumlist,outputfile): #print sumlist #print outputfile fobj=open(outputfile,'w') i=0 j=0 k=0 while i<self.row: while j<self.col: fobj.writelines(str(sumlist[k])+" "), j=j+1 k=k+1 j=0 fobj.writelines("\n") i=i+1 #return "wrote matrix in required file" #def check(self): # print self.elements #print self.file # print self.list # print self.col #print self.row m1=matrix('D:\mat1.txt') m2=matrix('D:\mat2.txt') #print type(m1) print m1 print print m2 #m3=matrix() m3=m1+m2 #m3=matrix(m3) #print m3 #print type(m3) m3.write(m3,'D:\mat3.txt') #print print m3 

except Exception,e: print e

1 Answer 1

1

You should return self instead of l.

Sign up to request clarification or add additional context in comments.

5 Comments

could you please elaborate a bit, because i am not able to get desired output by returning self. no doubt it is now returning the matrix type but i want my list to convert to matrix type.
or if there is any other way to solve this problem . might be i have started creating function in wrong direction. The biggest problem i am facing to convert a variable into matrix datatype is, i have too give a file as input. might be the code architecture is wrong.
How exactly do you want your matrix to look?
the aim of the question is
i want to display the matrix in matrix format only as well as i am copying final output to a file by using write function. i have taken m1 and m2 of matrix type i am using str function to display in matrix form now when i am adding two matrices m1 and m2 and storing in m3. and m3 is of type list. what i want is m3 should be of type matrix.so add function should return a matrix type. and once m3 will be of type matrix .i will call other function to write that matrix in a file. could you please correct me where i am doing wrong.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.