matriz de comparação in python

To create a matriz de comparação (comparison matrix) in Python, we can use the NumPy library which provides a very useful module called numpy.matlib. This module provides a variety of functions to work on matrices.

To create a comparison matrix, we need to first define a list of values that represent the order of preference of two given elements. For example, suppose we have four elements: A, B, C, and D. We need to define the order of preference between any two elements. Suppose we have the following preferences: A > B > C > D. This means that we prefer A over B, B over C, and so on.

To represent this information in a matrix, we can use the following code:

main.py
import numpy as np

# Define the order of preference
order = [1, 2, 3, 4]

# Create a zero matrix
n = len(order)
matrix = np.zeros(shape=(n, n))

# Fill the matrix
for i in range(n):
    for j in range(n):
        if order[i] > order[j]:
            matrix[i][j] = 1
        elif order[i] < order[j]:
            matrix[i][j] = -1

print(matrix)
346 chars
19 lines

In this code, we first define the order of preference as a list of integers. We then create a matrix of zeros with shape (n, n) where n is the length of the order list. This matrix will be filled with the preference values based on the comparisons between pairs of elements using a nested loop. Finally, we print the matrix.

The resulting matrix will look like this:

main.py
array([[ 0.,  1.,  1.,  1.],
       [-1.,  0.,  1.,  1.],
       [-1., -1.,  0.,  1.],
       [-1., -1., -1.,  0.]])
117 chars
5 lines

This matrix represents the order of preference between A, B, C, and D. The diagonal values are all zero because an element cannot be preferred over itself. The upper triangle of the matrix represents the preference of the rows over the columns, while the lower triangle represents the preference of the columns over the rows.

gistlibby LogSnag