# ============================================
# OPERACIONES CON MATRICES USANDO MENU
# ============================================
def definir_dimensiones():
while True:
try:
filas = int(input("Ingrese el número de filas: "))
columnas = int(input("Ingrese el número de columnas: "))
if filas > 0 and columnas > 0:
return filas, columnas
else:
print("Las dimensiones deben ser mayores que cero.")
except ValueError:
print("Error: ingrese valores enteros válidos.")
def crear_matriz(filas, columnas, valor=0):
return [[valor for _ in range(columnas)] for _ in range(filas)]
def llenar_matriz(nombre, filas, columnas):
matriz = []
print(f"\nLlenado de la matriz {nombre}")
for i in range(filas):
fila = []
for j in range(columnas):
while True:
try:
valor = float(input(f"{nombre}[{i}][{j}] = "))
fila.append(valor)
break
except ValueError:
print("Error: ingrese un valor numérico válido.")
matriz.append(fila)
return matriz
def desplegar_matriz(nombre, matriz):
print(f"\nMatriz {nombre}:")
for i in range(len(matriz)):
for j in range(len(matriz[0])):
print(f"{matriz[i][j]:10}", end=" ")
print()
def sumar_matrices(a, b):
filas = len(a)
columnas = len(a[0])
r = crear_matriz(filas, columnas)
for i in range(filas):
for j in range(columnas):
r[i][j] = a[i][j] + b[i][j]
return r
def restar_matrices(a, b):
filas = len(a)
columnas = len(a[0])
r = crear_matriz(filas, columnas)
for i in range(filas):
for j in range(columnas):
r[i][j] = a[i][j] - b[i][j]
return r
def multiplicar_matrices_elemento(a, b):
filas = len(a)
columnas = len(a[0])
r = crear_matriz(filas, columnas)
for i in range(filas):
for j in range(columnas):
r[i][j] = a[i][j] * b[i][j]
return r
def dividir_matrices_elemento(a, b):
filas = len(a)
columnas = len(a[0])
r = crear_matriz(filas, columnas)
for i in range(filas):
for j in range(columnas):
if b[i][j] == 0:
r[i][j] = "Indef"
else:
r[i][j] = a[i][j] / b[i][j]
return r
def matrices_definidas(a, b):
return len(a) > 0 and len(b) > 0
def mostrar_menu():
print("\n" + "=" * 55)
print("MENU DE OPERACIONES CON MATRICES")
print("=" * 55)
print("0) Tamaño de matrices A y B")
print("1) Llenado matriz A")
print("2) Llenado matriz B")
print("3) Suma A + B")
print("4) Resta A - B")
print("5) Multiplicación A * B (elemento a elemento)")
print("6) División A / B (elemento a elemento)")
print("7) Desplegar matriz A")
print("8) Desplegar matriz B")
print("9) Salir")
def main():
filas = 0
columnas = 0
A = []
B = []
while True:
mostrar_menu()
try:
opcion = int(input("Seleccione una opción: "))
except ValueError:
print("Error: debe ingresar un número entero.")
continue
if opcion == 0:
filas, columnas = definir_dimensiones()
A = crear_matriz(filas, columnas)
B = crear_matriz(filas, columnas)
print(f"Se definieron matrices de tamaño {filas}x{columnas}.")
elif opcion == 1:
if filas == 0 or columnas == 0:
print("Primero debe definir el tamaño de las matrices con la opción 0.")
else:
A = llenar_matriz("A", filas, columnas)
elif opcion == 2:
if filas == 0 or columnas == 0:
print("Primero debe definir el tamaño de las matrices con la opción 0.")
else:
B = llenar_matriz("B", filas, columnas)
elif opcion == 3:
if matrices_definidas(A, B):
R = sumar_matrices(A, B)
desplegar_matriz("A", A)
desplegar_matriz("B", B)
desplegar_matriz("R = A + B", R)
else:
print("Debe definir y llenar las matrices A y B.")
elif opcion == 4:
if matrices_definidas(A, B):
R = restar_matrices(A, B)
desplegar_matriz("A", A)
desplegar_matriz("B", B)
desplegar_matriz("R = A - B", R)
else:
print("Debe definir y llenar las matrices A y B.")
elif opcion == 5:
if matrices_definidas(A, B):
R = multiplicar_matrices_elemento(A, B)
desplegar_matriz("A", A)
desplegar_matriz("B", B)
desplegar_matriz("R = A * B", R)
else:
print("Debe definir y llenar las matrices A y B.")
elif opcion == 6:
if matrices_definidas(A, B):
R = dividir_matrices_elemento(A, B)
desplegar_matriz("A", A)
desplegar_matriz("B", B)
desplegar_matriz("R = A / B", R)
else:
print("Debe definir y llenar las matrices A y B.")
elif opcion == 7:
if len(A) > 0:
desplegar_matriz("A", A)
else:
print("La matriz A no está definida.")
elif opcion == 8:
if len(B) > 0:
desplegar_matriz("B", B)
else:
print("La matriz B no está definida.")
elif opcion == 9:
print("Programa finalizado.")
break
else:
print("Opción no válida. Intente nuevamente.")
# Ejecutar programa
main()