Compare matrix values and add them to another (python)

Asked

Viewed 403 times

-4

I am not able to make the structure to compare whether the value at the[l][c] position of one matrix is greater than at the same position of another, and if so, this value goes to that same position in a third matrix:

matrixOne = [[1, 12, 45], [58, 524, 78], [1, 2, 3], [45, 456, 8]]

matrixTwo = [[0, 1, 2], [85, 1, 74], [27, 63, 21], [25, 47, 962]]

matrixTrhee = [[], [], [], []]

for l in range(0, 4):

    for c in range(0, 4):

        if matrixOne[l][c] > matrixTwo[l][c]:

            matrixTrhee[l][c] = matrixOne[l][c]

        else:

            matrixTrhee[l][c] = matrixTwo[l][c]

for l in range(0, 4):

    for c in range(0, 4):

        print(f'[{matrixTrhee}{[l]}{[c]}:^5]', end=' ')

    print()
  • 1

    It is important to post a question and explain objectively and punctually the difficulty found, accompanied by a [mcve] of the problem and attempt to solve it. To understand what kind of question serves the site and, consequently, avoid closures and negativities worth reading What is the Stack Overflow and the Stack Overflow Survival Guide (summarized) in Portuguese. Remembering also that can [Dit] the posts at any time to improve the details.

2 answers

1


Running the question code:

matrixOne = [
[ 1,  12, 45], 
[58, 524, 78], 
[ 1,   2,  3],
[45, 456,  8]]

matrixTwo = [
[ 0,  1,  2], 
[85,  1,  74], 
[27, 63,  21], 
[25, 47, 962]]

#Inicializa a lista com todas as posições definidas
matrixTrhee = [[0,0,0] for _ in range(4)]

for l in range(0, 4):   
    #Aqui são três colunas e não quatro. 
    for c in range(0, 3):    
        if matrixOne[l][c] > matrixTwo[l][c]:    
            matrixTrhee[l][c]=matrixOne[l][c]    
        else:    
            matrixTrhee[l][c]=matrixTwo[l][c]

print(*matrixTrhee, sep="\n")
#[ 1,  12,  45]
#[85, 524,  78]
#[27,  63,  21]
#[45, 456, 962]

A more compact alternative would be to flatten (convert to vector 1D) the matrices and with the standard library method itertools, chain.from_iterable(iterable) and compare the corresponding pairs of matrix items.

The algorithm is simple:

  • Flatten a matrix and a enumerates the elements.
  • Flatten the other matrix.
  • Transition by the enumeration matrix and compare taking advantage of the indices which the higher value.
  • Regroup the result in the required matrix structure.

Example:

from itertools import chain

matrixOne = [
[ 1,  12, 45], 
[58, 524, 78], 
[ 1,   2,  3],
[45, 456,  8]]

matrixTwo = [
[ 0,  1,  2], 
[85,  1,  74], 
[27, 63,  21], 
[25, 47, 962]]


m1 = enumerate(chain.from_iterable(matrixOne))             #Achata e enumera matrixOne .
m2 = list(chain.from_iterable(matrixTwo))                  #Achata matrixTwo.
m3 = [max(v, m2[i]) for i, v in m1]                        #Itera por m1 e encontra o maior valor.

matrixTrhee= [m3[r: r+3] for r in range(0, len(m3), 3)]  #Reorganiza o resultado em uma matriz 4x3.

print(*matrixTrhee, sep="\n")
#[ 1,  12,  45]
#[85, 524,  78]
#[27,  63,  21]
#[45, 456, 962]

Test the code on Ideone

-2

One of the valid ways to resolve this issue is:

matrixOne = [[1, 12, 45], [58, 524, 78], [1, 2, 3], [45, 456, 8]]
matrixTwo = [[0, 1, 2], [85, 1, 74], [27, 63, 21], [25, 47, 962]]

matrixTrhee = []
for l in range(4):
    line = []
    for c in range(3):
        if matrixOne[l][c] > matrixTwo[l][c]:
            line.append(matrixOne[l][c])
        else:
            line.append(matrixTwo[l][c])
    matrixTrhee.append(line)

print(matrixTrhee)

Note that the first block for traverses the range(4) - equivalent to the number of rows in the matrix matrixTrhee. Then the second block for traverses the range(3) - equivalent to the number Dae columns of the matrix matrixTrhee - by checking whether each element of the matrixOne is greater than the corresponding element of matrixTwo. If yes, it will be added in line the element matrixOne[l][c]. Otherwise, the item matrixTwo[l][c] is added in line.

For each closure of 2nd block for is added line à matrixTrhee.

Finalizing the activities of the two blocks for the following output is displayed.

[[1, 12, 45], [85, 524, 78], [27, 63, 21], [45, 456, 962]]

Now, if you prefer to display the array in tabular form, you can use the numpy library. This way the code will be:

import numpy as np

matrixOne = [[1, 12, 45], [58, 524, 78], [1, 2, 3], [45, 456, 8]]
matrixTwo = [[0, 1, 2], [85, 1, 74], [27, 63, 21], [25, 47, 962]]

matrixTrhee = []
for l in range(4):
    line = []
    for c in range(3):
        if matrixOne[l][c] > matrixTwo[l][c]:
            line.append(matrixOne[l][c])
        else:
            line.append(matrixTwo[l][c])
    matrixTrhee.append(line)

print(np.array(matrixTrhee))

After performing all operations the following output will be displayed:

[[  1  12  45]
 [ 85 524  78]
 [ 27  63  21]
 [ 45 456 962]]

If you prefer you can also use List Comprehension. This way the code will stay:

import numpy as np

matrixOne = [[1, 12, 45], [58, 524, 78], [1, 2, 3], [45, 456, 8]]
matrixTwo = [[0, 1, 2], [85, 1, 74], [27, 63, 21], [25, 47, 962]]

matrixTrhee = [[matrixOne[l][c] if matrixOne[l][c] > matrixTwo[l][c] else matrixTwo[l][c]
                for c in range(3)] for l in range(4)]

print(np.array(matrixTrhee))

Producing the following output:

[[  1  12  45]
 [ 85 524  78]
 [ 27  63  21]
 [ 45 456 962]]

If there is no need to display delimiters - [] - we can use Generating Expressions. This way the code would be:

matrixOne = [[1, 12, 45], [58, 524, 78], [1, 2, 3], [45, 456, 8]]
matrixTwo = [[0, 1, 2], [85, 1, 74], [27, 63, 21], [25, 47, 962]]

matrixTrhee = ((matrixOne[l][c] if matrixOne[l][c] > matrixTwo[l][c] else matrixTwo[l][c]
                for c in range(3)) for l in range(4))

for i in matrixTrhee:
    for j in i:
        print(f'{j:>5}', end='')
    print()

Getting the following output:

    1   12   45
   85  524   78
   27   63   21
   45  456  962

Or, we can simply compare the values and display the results.

matrixOne = [[1, 12, 45], [58, 524, 78], [1, 2, 3], [45, 456, 8]]
matrixTwo = [[0, 1, 2], [85, 1, 74], [27, 63, 21], [25, 47, 962]]

print(f'A matrixTrhee é:')
for l in range(4):
    for c in range(3):
        if matrixOne[l][c] > matrixTwo[l][c]:
            print(f'{matrixOne[l][c]:>5}', end='')
        else:
            print(f'{matrixTwo[l][c]:>5}', end='')
    print()

Then we get the following output:

A matrixTrhee é:
    1   12   45
   85  524   78
   27   63   21
   45  456  962

Browser other questions tagged

You are not signed in. Login or sign up in order to post.