In [107]:
class Array:
"Constructor de matrices"
def __init__(self, list_of_rows):
"Constructor"
self.data = list_of_rows
self.shape = (len(list_of_rows), len(list_of_rows[0]))
def __repr__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
def __str__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
In [110]:
A = Array([[1,2,3],[4,5,6]])
In [111]:
print(A)
In [112]:
A
Out[112]:
In [113]:
class Array:
"Constructor de Matrices"
def __init__ (self, list_of_rows):
"Constructor"
#Obteción de dimensiones
self.data = list_of_rows
nrow=len(list_of_rows)
#Caso vector: redimensionar correctamente
#Si list_of_rows=[1,2,3] entonces list_of rows[0]=1 es un entero (no una lista)
if not isinstance(list_of_rows[0],list):
nrow=1
self.data = [[x] for x in list_of_rows]
#Con esto, self.data=[[1],[2],[3]]
#Se calcula en número de columnas y la dimensión
ncol=len(self.data[0])
self.shape=(nrow,ncol)
#Validador
if any ([len(r) != ncol for r in self.data]):
raise Exeption("Las filas deben ser del mismo tamano")
def __repr__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
def __str__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
In [114]:
A = Array([1,2,3])
In [115]:
print(A)
In [117]:
A
Out[117]:
In [118]:
A = Array([[1,2,3],[4,5,6]])
In [125]:
class Array:
"Constructor de Matrices"
def __init__ (self, list_of_rows):
"Constructor"
#Obteción de dimensiones
self.data = list_of_rows
nrow=len(list_of_rows)
#Caso vector: redimensionar correctamente
#Si list_of_rows=[1,2,3] entonces list_of rows[0]=1 es un entero (no una lista)
if not isinstance(list_of_rows[0],list):
nrow=1
self.data = [[x] for x in list_of_rows]
#Con esto, self.data=[[1],[2],[3]]
#Se calcula en número de columnas y la dimensión
ncol=len(self.data[0])
self.shape=(nrow,ncol)
#Validador
if any ([len(r) != ncol for r in self.data]):
raise Exeption("Las filas deben ser del mismo tamano")
def __repr__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
def __str__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
def __getitem__(self, idx):
return self.data[idx[0]][idx[1]]
def __setitem__(self, idx, new_value):
self.data[idx[0]][idx[1]]= new_value
In [126]:
A = Array([[1,2,3],[4,5,6]])
In [128]:
A[1,1]
Out[128]:
In [166]:
class Array:
"Constructor de Matrices"
def __init__ (self, list_of_rows):
"Constructor"
#Obteción de dimensiones
self.data = list_of_rows
nrow=len(list_of_rows)
#Caso vector: redimensionar correctamente
#Si list_of_rows=[1,2,3] entonces list_of rows[0]=1 es un entero (no una lista)
if not isinstance(list_of_rows[0],list):
nrow=1
self.data = [[x] for x in list_of_rows]
#Con esto, self.data=[[1],[2],[3]]
#Se calcula en número de columnas y la dimensión
ncol=len(self.data[0])
self.shape=(nrow,ncol)
#Validador
if any ([len(r) != ncol for r in self.data]):
raise Exeption("Las filas deben ser del mismo tamano")
def __repr__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
def __str__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
def __getitem__(self, idx):
return self.data[idx[0]][idx[1]]
def __setitem__(self, idx, new_value):
self.data[idx[0]][idx[1]]= new_value
def zeros(x,y):
"Matriz de ceros"
zeroarray= Array([[0 for col in range(y)]for row in range(x)])
return zeroarray
def eye(x):
"Matriz identidad"
identidad= Array([[0 for col in range(x)]for row in range(x)])
for a in range(x):
for b in range(x):
if a==b:
identidad[a,b]=1
return identidad
In [167]:
Ceros=Array.zeros(2,3)
In [168]:
Ceros
Out[168]:
In [169]:
Identidad=Array.eye(4)
In [170]:
Identidad
Out[170]:
In [191]:
class Array:
"Constructor de Matrices"
def __init__ (self, list_of_rows):
"Constructor"
#Obteción de dimensiones
self.data = list_of_rows
nrow=len(list_of_rows)
#Caso vector: redimensionar correctamente
#Si list_of_rows=[1,2,3] entonces list_of rows[0]=1 es un entero (no una lista)
if not isinstance(list_of_rows[0],list):
nrow=1
self.data = [[x] for x in list_of_rows]
#Con esto, self.data=[[1],[2],[3]]
#Se calcula en número de columnas y la dimensión
ncol=len(self.data[0])
self.shape=(nrow,ncol)
#Validador
if any ([len(r) != ncol for r in self.data]):
raise Exeption("Las filas deben ser del mismo tamano")
def __repr__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
def __str__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
def __getitem__(self, idx):
return self.data[idx[0]][idx[1]]
def __setitem__(self, idx, new_value):
self.data[idx[0]][idx[1]]= new_value
def zeros(x,y):
"Matriz de ceros"
zeroarray= Array([[0 for col in range(y)]for row in range(x)])
return zeroarray
def eye(x):
"Matriz identidad"
identidad= Array([[0 for col in range(x)]for row in range(x)])
for a in range(x):
for b in range(x):
if a==b:
identidad[a,b]=1
return identidad
def transpose(self):
"Matriz transpuesta"
nrow_t=len(self.data[0])
ncol_t=len(self.data)
transpuesta=Array([[0 for a in range(ncol_t)]for b in range(nrow_t)])
for a in range(nrow_t):
for b in range(ncol_t):
transpuesta[a,b]=self.data[b][a]
return transpuesta
In [192]:
A = Array([[1,2,3],[4,5,6]])
A
Out[192]:
In [193]:
trans=A.transpose()
trans
Out[193]:
In [212]:
class Array:
"Constructor de Matrices"
def __init__ (self, list_of_rows):
"Constructor"
#Obteción de dimensiones
self.data = list_of_rows
nrow=len(list_of_rows)
#Caso vector: redimensionar correctamente
#Si list_of_rows=[1,2,3] entonces list_of rows[0]=1 es un entero (no una lista)
if not isinstance(list_of_rows[0],list):
nrow=1
self.data = [[x] for x in list_of_rows]
#Con esto, self.data=[[1],[2],[3]]
#Se calcula en número de columnas y la dimensión
ncol=len(self.data[0])
self.shape=(nrow,ncol)
#Validador
if any ([len(r) != ncol for r in self.data]):
raise Exeption("Las filas deben ser del mismo tamano")
def __repr__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
def __str__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
def __getitem__(self, idx):
return self.data[idx[0]][idx[1]]
def __setitem__(self, idx, new_value):
self.data[idx[0]][idx[1]]= new_value
def zeros(x,y):
"Matriz de ceros"
zeroarray= Array([[0 for col in range(y)]for row in range(x)])
return zeroarray
def eye(x):
"Matriz identidad"
identidad= Array([[0 for col in range(x)]for row in range(x)])
for a in range(x):
for b in range(x):
if a==b:
identidad[a,b]=1
return identidad
def transpose(self):
"Matriz transpuesta"
nrow_t=len(self.data[0])
ncol_t=len(self.data)
transpuesta=Array([[0 for a in range(ncol_t)]for b in range(nrow_t)])
for a in range(nrow_t):
for b in range(ncol_t):
transpuesta[a,b]=self.data[b][a]
return transpuesta
def __add__(self, other):
"Suma de matrices o suma de un escalar"
if isinstance(other, Array):
if self.shape != other.shape:
raise Exception("Las dimensiones son distintas!")
rows, cols = self.shape
newArray = Array([[0. for c in range(cols)] for r in range(rows)])
for r in range(rows):
for c in range(cols):
newArray.data[r][c] = self.data[r][c] + other.data[r][c]
return newArray
elif isinstance(2, (int, float, complex)): # en caso de que el lado derecho sea solo un numero
rows, cols = self.shape
newArray = Array([[0. for c in range(cols)] for r in range(rows)])
for r in range(rows):
for c in range(cols):
newArray.data[r][c] = self.data[r][c] + other
return newArray
else:
return NotImplemented # es un tipo de error particular usado en estos metodos
__radd__ = __add__
def __sub__(self, other):
"Suma de matrices o suma de un escalar"
if isinstance(other, Array):
if self.shape != other.shape:
raise Exception("Las dimensiones son distintas!")
rows, cols = self.shape
newArray = Array([[0. for c in range(cols)] for r in range(rows)])
for r in range(rows):
for c in range(cols):
newArray.data[r][c] = self.data[r][c] - other.data[r][c]
return newArray
elif isinstance(2, (int, float, complex)): # en caso de que el lado derecho sea solo un numero
rows, cols = self.shape
newArray = Array([[0. for c in range(cols)] for r in range(rows)])
for r in range(rows):
for c in range(cols):
newArray.data[r][c] = self.data[r][c] - other
return newArray
else:
return NotImplemented # es un tipo de error particular usado en estos metodos
In [213]:
A = Array([[1,2], [3,4]])
B = Array([[5,6], [7,8]])
C = A - B
C.data
Out[213]:
In [214]:
D = A - 10
D
Out[214]:
In [215]:
1 + Array([[1,2], [3,4]])
Out[215]:
In [14]:
class Array:
"Constructor de Matrices"
def __init__ (self, list_of_rows):
"Constructor"
#Obteción de dimensiones
self.data = list_of_rows
nrow=len(list_of_rows)
#Caso vector: redimensionar correctamente
#Si list_of_rows=[1,2,3] entonces list_of rows[0]=1 es un entero (no una lista)
if not isinstance(list_of_rows[0],list):
nrow=1
self.data = [[x] for x in list_of_rows]
#Con esto, self.data=[[1],[2],[3]]
#Se calcula en número de columnas y la dimensión
ncol=len(self.data[0])
self.shape=(nrow,ncol)
#Validador
if any ([len(r) != ncol for r in self.data]):
raise Exeption("Las filas deben ser del mismo tamano")
def __repr__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
def __str__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
def __getitem__(self, idx):
return self.data[idx[0]][idx[1]]
def __setitem__(self, idx, new_value):
self.data[idx[0]][idx[1]]= new_value
def zeros(x,y):
"Matriz de ceros"
zeroarray= Array([[0 for col in range(y)]for row in range(x)])
return zeroarray
def eye(x):
"Matriz identidad"
identidad= Array([[0 for col in range(x)]for row in range(x)])
for a in range(x):
for b in range(x):
if a==b:
identidad[a,b]=1
return identidad
def transpose(self):
"Matriz transpuesta"
nrow_t=len(self.data[0])
ncol_t=len(self.data)
transpuesta=Array([[0 for a in range(ncol_t)]for b in range(nrow_t)])
for a in range(nrow_t):
for b in range(ncol_t):
transpuesta[a,b]=self.data[b][a]
return transpuesta
def __add__(self, other):
"Suma de matrices o suma matriz y escalar"
if isinstance(other, Array):
if self.shape != other.shape:
raise Exception("Las dimensiones son distintas!")
rows, cols = self.shape
newArray = Array([[0. for c in range(cols)] for r in range(rows)])
for r in range(rows):
for c in range(cols):
newArray.data[r][c] = self.data[r][c] + other.data[r][c]
return newArray
elif isinstance(2, (int, float, complex)): # en caso de que el lado derecho sea solo un numero
rows, cols = self.shape
newArray = Array([[0. for c in range(cols)] for r in range(rows)])
for r in range(rows):
for c in range(cols):
newArray.data[r][c] = self.data[r][c] + other
return newArray
else:
return NotImplemented # es un tipo de error particular usado en estos metodos
__radd__ = __add__
def __sub__(self, other):
"Resta de matrices o resta matriz y escalar"
if isinstance(other, Array):
if self.shape != other.shape:
raise Exception("Las dimensiones son distintas!")
rows, cols = self.shape
newArray = Array([[0. for c in range(cols)] for r in range(rows)])
for r in range(rows):
for c in range(cols):
newArray.data[r][c] = self.data[r][c] - other.data[r][c]
return newArray
elif isinstance(2, (int, float, complex)): # en caso de que el lado derecho sea solo un numero
rows, cols = self.shape
newArray = Array([[0. for c in range(cols)] for r in range(rows)])
for r in range(rows):
for c in range(cols):
newArray.data[r][c] = self.data[r][c] - other
return newArray
else:
return NotImplemented # es un tipo de error particular usado en estos metodos
def __mul__(self, other):
"Multiplicación de matrices o multiplicación de matriz por escalar"
if isinstance(other, Array):
if self.shape[1]!=other.shape[0]:
raise Expeption("Las dimensiones de las matrices no permiten hacer la multiplicación")
rowA=self.shape[0]
colA=self.shape[1]
rowB=other.shape[0]
colB=other.shape[1]
newArray = Array([[0. for l in range(colB)] for i in range(rowA)])
for i in range(rowA):
for l in range(colB):
for j in range(rowB):
newArray[i,l]= newArray[i,l] + self.data[i][j]*other.data[j][l]
return newArray
elif isinstance(other, (int,float, complex)):
rowA,colA= self.shape
newArray = Array([[0. for c in range(colA)] for r in range(rowA)])
for i in range (rowA):
for j in range(colA):
newArray.data[i][j]=self.data[i][j]*other
return newArray
else:
return NotImplemented
In [15]:
A = Array([[1,4], [2,5],[3,6]])
B = Array([[1,2,3], [4,5,6]])
A*B
Out[15]:
In [16]:
A.shape
Out[16]:
In [17]:
B.shape
Out[17]:
In [20]:
A
Out[20]:
In [21]:
A*2
Out[21]:
In [23]:
class Array:
"Constructor de Matrices"
def __init__ (self, list_of_rows):
"Constructor"
#Obteción de dimensiones
self.data = list_of_rows
nrow=len(list_of_rows)
#Caso vector: redimensionar correctamente
#Si list_of_rows=[1,2,3] entonces list_of rows[0]=1 es un entero (no una lista)
if not isinstance(list_of_rows[0],list):
nrow=1
self.data = [[x] for x in list_of_rows]
#Con esto, self.data=[[1],[2],[3]]
#Se calcula en número de columnas y la dimensión
ncol=len(self.data[0])
self.shape=(nrow,ncol)
#Validador
if any ([len(r) != ncol for r in self.data]):
raise Exeption("Las filas deben ser del mismo tamano")
def __repr__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
def __str__(self):
matriz=""
for x in self.data:
matriz = matriz + str(x)+"\n"
return matriz
def __getitem__(self, idx):
return self.data[idx[0]][idx[1]]
def __setitem__(self, idx, new_value):
self.data[idx[0]][idx[1]]= new_value
def zeros(x,y):
"Matriz de ceros"
zeroarray= Array([[0 for col in range(y)]for row in range(x)])
return zeroarray
def eye(x):
"Matriz identidad"
identidad= Array([[0 for col in range(x)]for row in range(x)])
for a in range(x):
for b in range(x):
if a==b:
identidad[a,b]=1
return identidad
def transpose(self):
"Matriz transpuesta"
nrow_t=len(self.data[0])
ncol_t=len(self.data)
transpuesta=Array([[0 for a in range(ncol_t)]for b in range(nrow_t)])
for a in range(nrow_t):
for b in range(ncol_t):
transpuesta[a,b]=self.data[b][a]
return transpuesta
def __add__(self, other):
"Suma de matrices o suma matriz y escalar"
if isinstance(other, Array):
if self.shape != other.shape:
raise Exception("Las dimensiones son distintas!")
rows, cols = self.shape
newArray = Array([[0. for c in range(cols)] for r in range(rows)])
for r in range(rows):
for c in range(cols):
newArray.data[r][c] = self.data[r][c] + other.data[r][c]
return newArray
elif isinstance(other, (int, float, complex)): # en caso de que el lado derecho sea solo un numero
rows, cols = self.shape
newArray = Array([[0. for c in range(cols)] for r in range(rows)])
for r in range(rows):
for c in range(cols):
newArray.data[r][c] = self.data[r][c] + other
return newArray
else:
return NotImplemented # es un tipo de error particular usado en estos metodos
__radd__ = __add__
def __sub__(self, other):
"Resta de matrices o resta matriz y escalar"
if isinstance(other, Array):
if self.shape != other.shape:
raise Exception("Las dimensiones son distintas!")
rows, cols = self.shape
newArray = Array([[0. for c in range(cols)] for r in range(rows)])
for r in range(rows):
for c in range(cols):
newArray.data[r][c] = self.data[r][c] - other.data[r][c]
return newArray
elif isinstance(other, (int, float, complex)): # en caso de que el lado derecho sea solo un numero
rows, cols = self.shape
newArray = Array([[0. for c in range(cols)] for r in range(rows)])
for r in range(rows):
for c in range(cols):
newArray.data[r][c] = self.data[r][c] - other
return newArray
else:
return NotImplemented # es un tipo de error particular usado en estos metodos
def __mul__(self, other):
"Multiplicación de matrices o multiplicación de matriz por escalar"
if isinstance(other, Array):
if self.shape[1]!=other.shape[0]:
raise Expeption("Las dimensiones de las matrices no permiten hacer la multiplicación")
rowA=self.shape[0]
colA=self.shape[1]
rowB=other.shape[0]
colB=other.shape[1]
newArray = Array([[0. for l in range(colB)] for i in range(rowA)])
for i in range(rowA):
for l in range(colB):
for j in range(rowB):
newArray[i,l]= newArray[i,l] + self.data[i][j]*other.data[j][l]
return newArray
elif isinstance(other, (int,float, complex)):
rowA,colA= self.shape
newArray = Array([[0. for c in range(colA)] for r in range(rowA)])
for i in range (rowA):
for j in range(colA):
newArray.data[i][j]=self.data[i][j]*other
return newArray
else:
return NotImplemented
def forward_subs (self,Y):
"Método para resolver una matriz triangular inferior"
if isinstance(Y,Array):
if Y.shape[1]!=1:
raise Exeption ("Y no es un vector")
if Y.shape[0]!=self.shape[1]:
raise Exeption ("Las dimensiones de las matrices no permiten hacer la operación")
rowA,colA= self.shape
for i in range(colA):
for j in range(rowA):
if i>j:
if self.data[j][i]!=0:
raise Exeption ("La matriz no es triangular inferior")
colY= Y.shape[0]
newArrayX = Array([[0.] for l in range(colY)])
for j in range(colY):
if j==0:
newArrayX.data[0][0]=(Y.data[0][0])/(self.data[0][0])
if j>0:
for i in range(j):
newArrayX.data[j][0]=newArrayX.data[j][0]-(self.data[j][i]/self.data[j][j])*newArrayX.data[i][0]
newArrayX.data[j][0]=Y.data[j][0]/self.data[j][j]+ newArrayX.data[j][0]
return newArrayX
def backward_subs (self,Y):
"Método para resolver una matriz triangular superior"
if isinstance(Y,Array):
if Y.shape[1]!=1:
raise Exeption ("Y no es un vector")
if Y.shape[0]!=self.shape[1]:
raise Exeption ("Las dimensiones de las matrices no permiten hacer la operación")
rowA,colA= self.shape
for i in range(colA):
for j in range(rowA):
if i<j:
if self.data[j][i]!=0:
raise Exeption ("La matriz no es triangular superior")
colY= Y.shape[0]
newArrayX = Array([[0.] for l in range(colY)])
for j in range(colY):
c=colY-j-1
if j==0:
newArrayX.data[c][0]=(Y.data[c][0])/(self.data[c][c])
if j>0:
for i in range(j):
q=c+1+i
newArrayX.data[c][0]=newArrayX.data[c][0]-(self.data[c][q]/self.data[c][c])*newArrayX.data[q][0]
newArrayX.data[c][0]=Y.data[c][0]/self.data[c][c]+ newArrayX.data[c][0]
return newArrayX
In [24]:
A = Array([[1,0,0], [2,3,0],[4,5,6]])
In [25]:
A
Out[25]:
In [26]:
Y =Array([[1],[2],[3]])
In [27]:
Y.shape
Out[27]:
In [28]:
X=A.forward_subs(Y)
In [29]:
X
Out[29]:
In [30]:
A = Array([[1,2,3], [0,4,5],[0,0,6]])
In [31]:
A
Out[31]:
In [32]:
X=A.backward_subs(Y)
In [34]:
X
Out[34]:
In [35]:
1/8
Out[35]: