0% found this document useful (0 votes)
28 views34 pages

Final Project

Uploaded by

daniel3127230537
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views34 pages

Final Project

Uploaded by

daniel3127230537
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Universidad

Tecnológica de Durango

Departamento de Mecatrónica y
Energías Renovables

Técnico Superior Universitario


en Mecatrónica

Algebra Lineal

Unidad III

Final Project

Cuatrimestre y grupo: 2ºC


Docente: M.C. Bárbara Patricia Carrales Campa

Victoria de Durango, Dgo a 29 de 04 de 2024


Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

Team Members: .............................................................................................................................. 2


Convert name to matrixes program: ......................................................... 2

Introduction .................................................................................................................................... 2
Description of the program ...................................................................... 3

Parts of the Code:............................................................................................................................ 3


1.-Imports .................................................................................................................................... 3
2.- Defining classes ...................................................................................................................... 4
3.- Initialize the matrices for each letter of the alphabet ........................................................... 4
4.- Add a matrix for the letter ñ .................................................................................................. 7
5.- Method to sum up all the matrices in a list ........................................................................... 8
6.- Method for calculating the determinant of a 3x3 matrix .................................................... 10
7.- Method for calculating the adjoint of a 3x3 matrix ............................................................. 11
8.- Method to calculate the inverse of a 3x3 matrix ................................................................. 13
9.- Method for calculating the transpose of a 3x3 matrix ........................................................ 15
10.- Setting a style for the pop-up window............................................................................... 17
11.- Create the user interface ................................................................................................... 18
12.- Create a label matrix to represent the table ..................................................................... 20
13.- Convert each character into its corresponding matrix (ignoring blanks) .......................... 22
14.- Print each individual matrix ............................................................................................... 24
15.-Add debug messages to see which letters and matrices are being used ........................... 25
16.-Add upp all the matrices ..................................................................................................... 25
17.- Calculate the determinant of the resultant matrix ............................................................ 26
18.- Calculate the adjoint of the resulting matrix ..................................................................... 27
19.- Calculate the inverse of the resulting matrix ..................................................................... 28
20.- Calculate the transpose of the resulting matrix and finalize the code. ............................. 29
operating guidelines .............................................................................. 31

Diferent Examples With Names .............................................................. 33

1
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

Team Members:

#Aldama Santos Yasser Arafath

#Leyva Razo Adriel Salvador

#Nava Soto Daniel Atzin

# Pérez Arámbula Rubén Antonio

Convert name to matrixes program:


Introduction

This name to matrix conversion program is made to perform operations with


3x3 matrices. It provides an easy-to-use interface for entering matrices in
alphabetic characters and offers calculation operations such as matrix addition,
determinant calculation, adjacency calculation, matrix inversion and transpose
calculation.

The program is a valuable tool for students, professionals and anyone who
wants to learn and understand matrix operations interactively. With an intuitive
graphical interface and a wide range of functions, it is easy to learn, verify and
experiment with matrix math.

2
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

Description of the program


Name to matrix Calculator is a Python program designed to perform various
matrix operations. It provides a graphical user interface (GUI) to enter matrices
using alphabetical letters and perform operations such as matrix addition, matrix
formula calculation, adjacency matrix calculation, inverse matrix calculation and
transpose matrix calculation. The program is built using the Tkinter library for
graphical interfaces and contains functions for performing matrix operations.

Parts of the Code:

Let's start breaking down the code part by part to see how it works from the
inside out

1.-Imports
1. import tkinter as tk
2. from tkinter import ttk, messagebox, scrolledtext

These lines import the necessary modules from Tkinter for building the GUI
application.

‘tkinter as tk’ imports the Tkinter module and renames it as tk.

‘from tkinter import ttk, messagebox, scrolledtext’ imports specific classes


and functions from Tkinter for creating themed widgets, displaying message boxes,
and creating scrolled text widgets.

3
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

2.- Defining classes


class MatricesSumaDeterminante:
# Diccionario para almacenar las matrices de cada letra
matrices_mayusculas = {}
matrices_minusculas = {}

This defines a class named MatricesSumaDeterminante to encapsulate


the functionality related to matrix operations.

It includes class variables matrices_mayusculas and


matrices_minusculas to store matrices corresponding to uppercase and
lowercase letters, respectively.

3.- Initialize the matrices for each letter of the alphabet


# Inicializar las matrices para cada letra del alfabeto
@staticmethod
def initialize_matrices():
# Inicializar valores para letras mayúsculas
value_upper = 28

for c in range(ord('A'), ord('Z') + 1):


MatricesSumaDeterminante.matrices_mayusculas[chr(c)] = [
[value_upper, value_upper + 1, value_upper + 2],
[value_upper + 3, value_upper + 4, value_upper + 5],
[value_upper + 6, value_upper + 7, value_upper + 8]
]
value_upper += 1

# Inicializar valores para letras minúsculas


value_lower = 1

for c in range(ord('a'), ord('z') + 1):


MatricesSumaDeterminante.matrices_minusculas[chr(c)] = [
[value_lower, value_lower + 1, value_lower + 2],
[value_lower + 3, value_lower + 4, value_lower + 5],
[value_lower + 6, value_lower + 7, value_lower + 8]
]
value_lower += 1
This is a static method to initialize matrices for uppercase and lowercase letters
from 'A' to 'Z'

4
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

It assigns a specific pattern of values to each letter and stores the corresponding
matrices in the 'matrices_minusculas' and 'matrices_minusculas' dictionary.

3.1.-How it works

This part of the code initializes matrices for each letter of the alphabet, both
uppercase and lowercase.

1. @staticmethod: This decorator indicates that the method


initialize_matrices is a static method, meaning it's bound to the class
rather than an instance of the class.

2. initialize_matrices(): This method initializes matrices for each letter of


the alphabet.

3. value_upper = 28: This variable initializes the starting value for the
matrices of uppercase letters.

4. for c in range(ord('A'), ord('Z') + 1): This loop iterates over the


uppercase letters from 'A' to 'Z' using their ASCII values.

5. MatricesSumaDeterminante.matrices_mayusculas[chr(c)]: This
assigns a 3x3 matrix to each uppercase letter in the
‘matrices_mayusculas’ dictionary.

6. value_upper += 1: This increments the value for the next matrix.

7. value_lower = 1: This variable initializes the starting value for the


matrices of lowercase letters.

8. for c in range(ord('a'), ord('z') + 1): This loop iterates over the


lowercase letters from 'a' to 'z' using their ASCII values.

5
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

9. MatricesSumaDeterminante.matrices_minusculas[chr(c)]: This
assigns a 3x3 matrix to each lowercase letter in the
‘matrices_minusculas’ dictionary.

10. value_lower += 1: This increments the value for the next matrix.

In summary, this part of the code creates 3x3 matrices for each letter of the
alphabet, both uppercase and lowercase, and stores them in separate dictionaries
matrices_mayusculas and matrices_minusculas.

6
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

4.- Add a matrix for the letter ñ


As the alphabet we are using is the American alphabet, it does not use the letter ñ,
we will have to give it a separate value

# Agregar matriz para la letra "ñ"


MatricesSumaDeterminante.matrices_minusculas['ñ'] = [
[27, 28, 29],
[30, 31, 32],
[33, 34, 35]
]

This line assigns a 3x3 matrix to the key 'ñ' in the ‘matrices_minusculas’
dictionary. The values in the matrix are arbitrary integers.

# Agregar matriz para la letra "Ñ"


MatricesSumaDeterminante.matrices_mayusculas['Ñ'] = [
[54, 55, 56],
[57, 58, 59],
[60, 61, 62]
]

Similarly, this line assigns a 3x3 matrix to the key 'Ñ' in the
‘matrices_mayusculas’ dictionary.

These matrices are added to handle the special cases of "ñ" and "Ñ" in the input
strings. They follow the same pattern as the other matrices, with arbitrary integer
values.

7
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

5.- Method to sum up all the matrices in a list


# Método para sumar todas las matrices en una lista
@staticmethod
def sum_matrices(matrices):
result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

for matrix in matrices:


for i in range(3):
for j in range(3):
result[i][j] += matrix[i][j]

return result

This part of the code defines a static method called sum_matrices. Let's break
down its syntax and functionality:

• @staticmethod: This is a decorator in Python used to define a method as


a static method, meaning it belongs to the class rather than an instance of
the class. Static methods don't operate on instances and don't have access
to instance attributes. They are defined using the @staticmethod
decorator because they don't need access to instance-specific data.

• def sum_matrices(matrices):: This line defines the method


sum_matrices. It takes one argument matrices, which is expected to be
a list of 3x3 matrices.

• result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]: This line initializes a 3x3 matrix
called result with all elements set to zero. This matrix will store the sum of
all matrices in the input list.

• for matrix in matrices:: This line starts a loop that iterates over each
matrix in the matrices list.

8
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

• for i in range(3):: This line starts a loop that iterates over the rows of the
matrix (indices 0, 1, and 2).

• for j in range(3):: This line starts a loop that iterates over the columns of
the matrix (indices 0, 1, and 2).

• result[i][j] += matrix[i][j]: This line adds the corresponding elements


of the current matrix being iterated over (matrix[i][j]) to the
corresponding elements of the result matrix. It effectively performs
element-wise addition.

• return result: Once all matrices in the input list have been summed up,
the resulting matrix result is returned.

9
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

6.- Method for calculating the determinant of a 3x3 matrix


# Método para calcular la determinante de una matriz 3x3
@staticmethod
def determinant(matrix):
det = (matrix[0][0] * (matrix[1][1] * matrix[2][2] - matrix[1][2] *
matrix[2][1]) -
matrix[0][1] * (matrix[1][0] * matrix[2][2] - matrix[1][2] *
matrix[2][0]) +
matrix[0][2] * (matrix[1][0] * matrix[2][1] - matrix[1][1] *
matrix[2][0]))
return det

This part of the code defines a static method called determinant within the
MatricesSumaDeterminante class.

• @staticmethod: This decorator marks the following method as a static


method, meaning it's associated with the class rather than instances of the
class. Static methods don't require access to instance-specific data.

• def determinant(matrix):: This line defines the method determinant,


which takes a single argument matrix, representing a 3x3 matrix for which
the determinant will be calculated.

• det = (matrix[0][0] * (matrix[1][1] * matrix[2][2] - matrix[1][2]


* matrix[2][1]) -: This line calculates the determinant of the given matrix
using the formula for a 3x3 matrix determinant. It's expressed in a single
line for brevity but follows the expansion of the determinant formula using
the elements of the matrix.

• return det: After calculating the determinant, the result is returned.

10
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

7.- Method for calculating the adjoint of a 3x3 matrix


def adjugate(matrix):
adj = [
[matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1], -
(matrix[0][1] * matrix[2][2] - matrix[0][2] * matrix[2][1]), matrix[0][1] *
matrix[1][2] - matrix[0][2] * matrix[1][1]],
[-(matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0]),
matrix[0][0] * matrix[2][2] - matrix[0][2] * matrix[2][0], -(matrix[0][0] *
matrix[1][2] - matrix[0][2] * matrix[1][0])],
[matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0], -
(matrix[0][0] * matrix[2][1] - matrix[0][1] * matrix[2][0]), matrix[0][0] *
matrix[1][1] - matrix[0][1] * matrix[1][0]]
]
return adj

This part of the code defines a function named adjugate that calculates the
adjugate matrix of a given 3x3 matrix. Let's break down its syntax and how it
works:

def adjugate(matrix):

‘def adjugate(matrix):’: This line defines the ‘adjugate’ function, which


takes a single argument ‘matrix’, representing the 3x3 matrix for which the
adjugate will be calculated.

11
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

• adj = [
• [matrix[1][1] * matrix[2][2] - matrix[1][2] *
matrix[2][1], -(matrix[0][1] * matrix[2][2] - matrix[0][2] *
matrix[2][1]), matrix[0][1] * matrix[1][2] - matrix[0][2] *
matrix[1][1]],
• [-(matrix[1][0] * matrix[2][2] - matrix[1][2] *
matrix[2][0]), matrix[0][0] * matrix[2][2] - matrix[0][2] *
matrix[2][0], -(matrix[0][0] * matrix[1][2] - matrix[0][2] *
matrix[1][0])],
• [matrix[1][0] * matrix[2][1] - matrix[1][1] *
matrix[2][0], -(matrix[0][0] * matrix[2][1] - matrix[0][1] *
matrix[2][0]), matrix[0][0] * matrix[1][1] - matrix[0][1] *
matrix[1][0]]
• ]

• This block initializes the variable ‘adj´ with a nested list comprehension that
calculates each element of the adjugate matrix based on the elements of
the input ‘matrix’. It follows the formula for computing the adjugate matrix
of a 3x3 matrix.

• return adj

Finally, the function returns the calculated adjugate matrix.

12
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

8.- Method to calculate the inverse of a 3x3 matrix


@staticmethod
def inverse(matrix):
det = MatricesSumaDeterminante.determinant(matrix)
if det == 0:
return None # La matriz no es invertible

adj = MatricesSumaDeterminante.adjugate(matrix)
inv = [[adj[i][j] / det for j in range(3)] for i in range(3)]
return inv

This part of the code defines a static method named ‘inverse’ within the
‘MatricesSumaDeterminante’ class. It computes the inverse of a given 3x3
matrix:

@staticmethod
def inverse(matrix):
• def inverse(matrix):: This line defines the inverse method, which takes
a single argument matrix, representing the 3x3 matrix for which the
inverse will be calculated.

• det = MatricesSumaDeterminante.determinant(matrix)

• This line calculates the determinant of the input matrix using the
determinant method defined within the MatricesSumaDeterminante
class.

13
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

if det == 0:
return None # La matriz no es invertible

• If the determinant is equal to zero, it means the matrix is not invertible. In


this case, the method returns ‘None’ to indicate that the inverse does not
exist.

• adj = MatricesSumaDeterminante.adjugate(matrix)

• The method calculates the adjugate matrix of the input matrix using the
adjugate method defined within the MatricesSumaDeterminante class.

• inv = [[adj[i][j] / det for j in range(3)] for i in range(3)]

• This line computes the elements of the inverse matrix by dividing each
element of the adjugate matrix by the determinant.

• return inv

• Finally, the method returns the calculated inverse matrix.

14
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

9.- Method for calculating the transpose of a 3x3 matrix


@staticmethod
def transpose(matrix):
return [[matrix[j][i] for j in range(3)] for i in range(3)]

def __init__(self):
self.initialize_matrices()
self.root = tk.Tk()
self.root.title("Calculadora de Determinante")
ruta_icono = "icon.ico"
try:
self.root.iconbitmap(ruta_icono)
except:
print("a")
self.root.geometry("530x330") # Ancho x Alto

This code initializes the matrices and creates the main application window for the
determinant calculator

@staticmethod
def transpose(matrix):
return [[matrix[j][i] for j in range(3)] for i in range(3)]

• def transpose(matrix):: This line defines the transpose method, which


takes a single argument matrix, representing the 3x3 matrix to be
transposed.

• return [[matrix[j][i] for j in range(3)] for i in range(3)]

• This line returns a new 2D list, which represents the transpose of the input
matrix. It uses a list comprehension to iterate over the rows and columns of
the input matrix and construct the transpose matrix accordingly.

15
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

def __init__(self):
self.initialize_matrices()
self.root = tk.Tk()
self.root.title("Calculadora de Determinante")
ruta_icono = "icon.ico"
try:
self.root.iconbitmap(ruta_icono)
except:
print("a")
self.root.geometry("530x330") # Ancho x Alto

• This code block defines the __init__ method, which serves as the
constructor for the MatricesSumaDeterminante class. It initializes the
class attributes and creates the main window for the calculator application
using the Tkinter library.

• self.initialize_matrices(): It calls the initialize_matrices method to


initialize the matrices for uppercase and lowercase letters.

• self.root = tk.Tk(): It creates the main application window using the Tk


class from the Tkinter library.

• self.root.title("Calculadora de Determinante"): It sets the title of the


application window to "Calculadora de Determinante".

• ruta_icono = "icon.ico": It defines the path to the icon file for the
application window.

• self.root.iconbitmap(ruta_icono): It tries to set the application window


icon using the specified icon file path. If an error occurs (e.g., the file does
not exist), it prints "a".

• self.root.geometry("530x330"): It sets the initial size of the application


window to 530 pixels wide and 330 pixels tall.

16
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

10.- Setting a style for the pop-up window


# Establecer un estilo para la ventana
self.style = ttk.Style()
self.style.theme_use("clam") # Cambiar el tema a "clam" (puedes
elegir otro tema según tus preferencias)

This part of the code sets a style for the window using the ‘ttk.Style()’
class from the tkinter library. It then specifies the theme to be used for the
style, which is "clam" in this case.

The ttk.Style() class allows you to define and customize the appearance of
widgets in your tkinter application. By calling
self.style.theme_use("clam"), the code sets the theme of the
application to "clam", which is one of the predefined themes available in
tkinter.

Choosing a theme is a matter of personal preference and can be adjusted


according to the desired look and feel of the application.

17
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

11.- Create the user interface


This section of the code creates a user interface with several widgets inside
a frame:

# Crear un marco para contener los widgets


self.main_frame = ttk.Frame(self.root, padding="20")
self.main_frame.pack(fill=tk.BOTH, expand=True)

# Etiqueta para ingresar un nombre


self.label = ttk.Label(self.main_frame, text="Ingrese un nombre:")
self.label.grid(row=0, column=0, padx=5, pady=5, sticky=tk.W)

# Campo de entrada para el nombre


self.entry = ttk.Entry(self.main_frame)
self.entry.bind('<Return>', self.calculate)
self.entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.W+tk.E)

# Botón para calcular


self.button = tk.Button(self.main_frame, text="Calcular",
command=self.calculate, font=("Arial", 10), bg="lightblue", width=15)
self.button.grid(row=0, column=2, padx=5, pady=5, sticky=tk.E)

# Cuadro de texto desplazable para mostrar los resultados


self.result_text = scrolledtext.ScrolledText(self.main_frame,
height=8, width=40)
self.result_text.grid(row=1, column=0, columnspan=3, padx=5, pady=5,
sticky=tk.W+tk.E+tk.N+tk.S)

18
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

Here's what each widget does:

1. Frame (self.main_frame): Acts as a container for other widgets,


providing structure and organization.

2. Label (self.label): Displays a text prompt for the user to enter a name.

3. Entry (self.entry): Provides a text entry field where the user can input a
name. It is binded to the <Return> key, so pressing Enter triggers the
self.calculate method.

4. Button (self.button): When clicked, it triggers the self.calculate


method. It has text "Calculate", with a specific font, background color, and
size.

5. ScrolledText (self.result_text): A text box that can display multiple lines


of text. It's configured to be scrollable both horizontally and vertically. This
widget will display the results of the calculations.

19
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

12.- Create a label matrix to represent the table


# Crear una matriz de etiquetas para representar la tabla
self.label_det = ttk.Label(self.main_frame, text="Determinante: ")
self.label_det.grid(row=1, column=3, padx=5, pady=5, sticky=tk.W)

self.label_sum = ttk.Label(self.main_frame, text="Resultante")


self.label_sum.grid(row=2, column=0, padx=5, pady=5, sticky=tk.W)
self.matriz_suma = tk.Label(self.main_frame, background="#DCDAD5")
self.matriz_suma.grid(row=3, column=0, columnspan=3, padx=5, pady=5,
sticky=tk.W+tk.E+tk.N+tk.S)

self.label_adj = ttk.Label(self.main_frame, text="Adjunta")


self.label_adj.grid(row=2, column=1, padx=5, pady=5, sticky=tk.W)
self.matriz_adj = tk.Label(self.main_frame, background="#DCDAD5")
self.matriz_adj.grid(row=3, column=1, columnspan=3, padx=5, pady=5,
sticky=tk.W+tk.E+tk.N+tk.S)

self.label_inv = ttk.Label(self.main_frame, text="Inversa")


self.label_inv.grid(row=2, column=2, padx=5, pady=5, sticky=tk.W)
self.matriz_inv = tk.Label(self.main_frame, background="#DCDAD5")
self.matriz_inv.grid(row=3, column=2, columnspan=3, padx=5, pady=5,
sticky=tk.W+tk.E+tk.N+tk.S)

self.label_tras = ttk.Label(self.main_frame, text="Traspuesta")


self.label_tras.grid(row=2, column=3, padx=5, pady=5, sticky=tk.W)
self.matriz_tras = tk.Label(self.main_frame, background="#DCDAD5")
self.matriz_tras.grid(row=3, column=3, columnspan=3, padx=5, pady=5,
sticky=tk.W+tk.E+tk.N+tk.S)

def calculate(self, event=None):


input_string = self.entry.get()

matrices_input = []
This part of the code creates a matrix of labels to represent a table in the
graphical user interface (GUI). Here's what each part does:

20
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

1. Label for Determinant (‘self.label_det’): This label displays the text


"Determinant:". It's positioned at row 1 and column 3 of the grid layout
within self.main_frame.

2. Label for Resultant (‘self.label_sum’): This label displays the text


"Resultant". It's positioned at row 2 and column 0 of the grid layout within
self.main_frame.

3. Label for Adjoint (‘self.label_adj’): This label displays the text "Adjoint".
It's positioned at row 2 and column 1 of the grid layout within
self.main_frame.

4. Label for Inverse (‘self.label_inv’): This label displays the text


"Inverse". It's positioned at row 2 and column 2 of the grid layout within
self.main_frame.

5. Label for Transpose (‘self.label_tras’): This label displays the text


"Transpose". It's positioned at row 2 and column 3 of the grid layout within
self.main_frame.

6. Labels for Matrices (‘self.matriz_suma, self.matriz_adj,


self.matriz_inv, self.matriz_tras’): These labels are used to display
matrices or their properties. They are initially configured with a background
color of "#DCDAD5". They are positioned at row 3 and their respective
columns within ‘self.main_frame’. Each label represents a different
property of the matrix, such as the sum, adjoint, inverse, or transpose.

21
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

13.- Convert each character into its corresponding matrix (ignoring


blanks)
# Convertir cada carácter en su matriz correspondiente (ignorando espacios
en blanco)
for c in input_string:
if c != ' ':
if c.isupper() and c in
MatricesSumaDeterminante.matrices_mayusculas:
matrices_input.append((c,
MatricesSumaDeterminante.matrices_mayusculas[c]))
elif c.islower() and c in
MatricesSumaDeterminante.matrices_minusculas:
matrices_input.append((c,
MatricesSumaDeterminante.matrices_minusculas[c]))
else:
messagebox.showwarning("Advertencia", f"Carácter '{c}'
no válido, se ignorará.")

result_str = ""

This part of the code processes each character in the input string and
converts it into its corresponding matrix. Here's how it works:

1. Loop Through Characters:

• The code iterates over each character, ‘c’, in the ‘input_string.’

22
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

2. Check for Valid Characters:

• If ‘c’is not a space (i.e., it's an actual character):

• It checks if ‘c’ is uppercase and if it exists in the


‘matrices_mayusculas’ dictionary of the
‘MatricesSumaDeterminante’ class. If both conditions are
met, it appends a tuple ‘(c,
MatricesSumaDeterminante.matrices_mayusculas[c])’
to the ‘matrices_input’ list. This tuple represents the
uppercase letter c and its corresponding matrix.

• If ‘c’ is lowercase and exists in the ‘matrices_minusculas’


dictionary, it appends a similar tuple for the lowercase letter.

• If ‘c’ is neither uppercase nor lowercase, or if it doesn't exist


in the predefined matrices, it displays a warning message
using ‘messagebox.showwarning()’, indicating that the
character will be ignored.

3. Result String:

• ‘result_str’ is initialized as an empty string. It will be used to


accumulate information about the matrices and any warnings
encountered during processing.

23
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

14.- Print each individual matrix


# Imprimir cada matriz individual
for i, (letter, matrix) in enumerate(matrices_input, start=1):
result_str += f"Matriz {i} (Letra '{letter}'):\n"
for row in matrix:
result_str += ' '.join(map(str, row)) + '\n'
result_str += '\n

This part of the code iterates over each matrix in the matrices_input list and
appends information about each matrix to the result_str string.

1. Iteration with Enumeration:

• It iterates over each element (letter, matrix) in the


matrices_input list using enumerate(matrices_input,
start=1).

• The enumerate() function provides a counter i starting from 1


along with each element (letter, matrix).

2. Appending Matrix Information:

• For each matrix, it appends a header to result_str indicating the


matrix number (using the counter i) and the corresponding letter.

• Then, it iterates over each row in the matrix and appends the values
of each row, separated by spaces, to result_str.

• After appending all rows of the matrix, it adds a newline character to


separate this matrix from the next one.

3. Result String:

• result_str accumulates information about each matrix, including its


number, corresponding letter, and the values in each row.

24
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

15.-Add debug messages to see which letters and matrices are being
used
# Agregar mensajes de depuración para ver qué letras y matrices se están
utilizando
print("Letras ingresadas:", [letter for letter, _ in
matrices_input])
print("Matrices utilizadas:", [matrix for _, matrix in
matrices_input])

This part was added, more to help programmers see in the terminal which arrays
were being used, making it easier to detect errors in code execution.

16.-Add upp all the matrices


# Sumar todas las matrices
if matrices_input:
sum_matrix = self.sum_matrices([matrix for _, matrix in
matrices_input])

result_str += "Matriz resultante de la suma:\n"


for row in sum_matrix:
result_str += ' '.join(map(str, row)) + '\n'

for fila in range(3):


for columna in range(3):
etiqueta = tk.Label(self.matriz_suma,
text="{}".format(sum_matrix[fila][columna]), borderwidth=1, relief="solid",
width=4, height=1)
etiqueta.grid(row=fila, column=columna)

This part of the code sums up all the matrices provided as input, displays the
resultant matrix in text form, and visualizes it using Tkinter labels.

25
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

17.- Calculate the determinant of the resultant matrix


# Calcular la determinante de la matriz resultante
det = self.determinant(sum_matrix)
result_str += f"\nLa determinante de la matriz resultante es:
{det}\n"
self.label_det["text"] = "Determinante: " + str(det)

This section of the code calculates the determinant of the resultant matrix
(sum_matrix) obtained from the sum of input matrices. Here's what each line
does:
1. det = self.determinant(sum_matrix): It calculates the determinant of
the sum_matrix by calling the determinant method defined in the class,
passing the sum_matrix as an argument. The determinant value is
assigned to the variable det.
2. result_str += f"\nLa determinante de la matriz resultante es:
{det}\n": It appends a string to the result_str variable, indicating the
determinant of the resultant matrix. The determinant value (det) is
formatted into the string using an f-string.
3. self.label_det["text"] = "Determinante: " + str(det): It updates the
text displayed on a label (label_det) in the GUI to show the calculated
determinant value. The str(det) converts the determinant value to a string,
and it's concatenated with the label text "Determinante: ".

26
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

18.- Calculate the adjoint of the resulting matrix

# Calcular la adjunta de la matriz resultante


adj = self.adjugate(sum_matrix)
result_str += "Matriz adjunta de la matriz resultante:\n"
for row in adj:
result_str += ' '.join(map(str, row)) + '\n'

for fila in range(3):


for columna in range(3):
etiqueta = tk.Label(self.matriz_adj,
text="{}".format(adj[fila][columna]), borderwidth=1, relief="solid",
width=4, height=1)
etiqueta.grid(row=fila, column=columna)

This part of the code calculates the adjugate (or adjoint) matrix of the resultant
matrix (sum_matrix). Here's a breakdown:
1. adj = self.adjugate(sum_matrix): It calculates the adjugate matrix of
the sum_matrix by calling the adjugate method defined in the class,
passing the sum_matrix as an argument. The resulting adjugate matrix is
stored in the variable adj.
2. result_str += "Matriz adjunta de la matriz resultante:\n": It
appends a string to the result_str variable, indicating that the following
lines will display the adjugate matrix of the resultant matrix.
3. for row in adj: and result_str += ' '.join(map(str, row)) + '\n':
These lines iterate over each row of the adjugate matrix (adj) and convert
each row's elements to strings, joining them with spaces. This forms a row
of the adjugate matrix, which is appended to the result_str.
4. for fila in range(3): and for columna in range(3):: These nested loops
iterate over the rows and columns of the adjugate matrix.
5. Inside these loops, it creates tk.Label widgets to display each element of
the adjugate matrix visually in the GUI. Each label is configured with the
corresponding element from the adjugate matrix (adj[fila][columna]).
These labels are then positioned in a grid layout within the matriz_adj
frame, representing the adjugate matrix visually.

27
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

19.- Calculate the inverse of the resulting matrix


# Calcular la inversa de la matriz resultante
inv = self.inverse(sum_matrix)
if inv:
result_str += "\nMatriz inversa de la matriz resultante:\n"
for row in inv:
result_str += ' '.join(map(str, row)) + '\n'
else:
result_str += "\nLa matriz resultante no es invertible.\n"
inv = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]

for fila in range(3):


for columna in range(3):
etiqueta = tk.Label(self.matriz_inv,
text="{}".format(inv[fila][columna]), borderwidth=1, relief="solid",
width=3, height=1)
etiqueta.grid(row=fila, column=columna)

This part of the code calculates the adjugate (or adjoint) matrix of the resultant
matrix (sum_matrix). Here's a breakdown:
1. adj = self.adjugate(sum_matrix): It calculates the adjugate matrix of
the sum_matrix by calling the adjugate method defined in the class,
passing the sum_matrix as an argument. The resulting adjugate matrix is
stored in the variable adj.
2. result_str += "Matriz adjunta de la matriz resultante:\n": It
appends a string to the result_str variable, indicating that the following
lines will display the adjugate matrix of the resultant matrix.
3. for row in adj: and result_str += ' '.join(map(str, row)) + '\n':
These lines iterate over each row of the adjugate matrix (adj) and convert
each row's elements to strings, joining them with spaces. This forms a row
of the adjugate matrix, which is appended to the result_str.
4. for fila in range(3): and for columna in range(3):: These nested loops
iterate over the rows and columns of the adjugate matrix.
5. Inside these loops, it creates tk.Label widgets to display each element of
the adjugate matrix visually in the GUI. Each label is configured with the
corresponding element from the adjugate matrix (adj[fila][columna]).
These labels are then positioned in a grid layout within the matriz_adj
frame, representing the adjugate matrix visually.

28
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

20.- Calculate the transpose of the resulting matrix and finalize the code.
# Calcular la transpuesta de la matriz resultante
trans = self.transpose(sum_matrix)
result_str += "Matriz transpuesta de la matriz resultante:\n"
for row in trans:
result_str += ' '.join(map(str, row)) + '\n'

for fila in range(3):


for columna in range(3):
etiqueta = tk.Label(self.matriz_tras,
text="{}".format(trans[fila][columna]), borderwidth=1, relief="solid",
width=4, height=1)
etiqueta.grid(row=fila, column=columna)

else:
messagebox.showerror("Error", "No se ingresaron caracteres
válidos.")

self.result_text.delete(1.0, tk.END)
self.result_text.insert(tk.END, result_str)

def run(self):
self.root.mainloop()

if __name__ == "__main__":
programa = MatricesSumaDeterminante()
programa.run()

This part of the code performs the following tasks:

1. Calculating the transpose of the resultant matrix:


• trans = self.transpose(sum_matrix): It calculates the transpose
of the resultant matrix (sum_matrix) by calling the transpose
method defined in the class and passing sum_matrix as an
argument. The resulting transpose matrix is stored in the variable
trans.
2. Appending to the result string:
• result_str += "Matriz transpuesta de la matriz
resultante:\n": This line appends a string indicating that the

29
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

following lines will display the transpose matrix of the resultant


matrix.
• for row in trans: and result_str += ' '.join(map(str, row)) +
'\n': These lines iterate over each row of the transpose matrix
(trans), convert each row's elements to strings, join them with
spaces, and append them to the result_str. This creates a string
representation of the transpose matrix.
3. Displaying the transpose matrix in the GUI:
• for fila in range(3): and for columna in range(3):: These nested
loops iterate over the rows and columns of the transpose matrix.
• Inside these loops, it creates tk.Label widgets to display each
element of the transpose matrix visually in the GUI. Each label is
configured with the corresponding element from the transpose matrix
(trans[fila][columna]). These labels are then positioned in a grid
layout within the matriz_tras frame, representing the transpose
matrix visually.
4. Handling invalid input:
• If no valid characters are entered, it displays an error message box
using messagebox.showerror.
5. Updating the result text widget:
• Finally, it updates the result_text widget in the GUI with the
computed result string using self.result_text.insert.
6. run method:
• This method starts the main event loop of the Tkinter application,
allowing the GUI to be displayed and interacted with by the user.

30
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

operating guidelines
1.- First open the program, is recommended create an direct access after
downloading it

2.- After opening the program it should appear this window

31
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

3.- In the input space next to “Ingrese un Nombre” place a name, which can
include both uppercase and lowercase words (do not enter special characters [, . ""
; : ... @ ", or accented words ] since it will mark an error in the console and take
the character as null, as well as characters with dieresis or belonging to other
alphabets than the basic Latin alphabet)

4.- Click on the "Calcular" button, and the program will show you different
matrices that are made with the entered name (individual matrix of each letter, the
sum of matrices, determinant of the resulting matrix, adjoint matrix, transposed
matrix and inverse matrix).

32
Técnico Superior Universitario en Mecatrónica
Algebra Lineal
Unidad III

Diferent Examples With Names

33

You might also like