Matrix multiplication

Asked

Viewed 3,871 times

1

Could you help with Matrix in python?! The exercise is as follows, a function matriz_mult(n1, n2) takes two matrices as parameter and returns True if the matrices are multiplied in the given order and False otherwise.

The way out must be something like :

n1 = [[1, 2, 3], [4, 5, 6]]
n2 = [[2, 3, 4], [5, 6, 7]]
matriz_mult(n1, n2) => False

n1 = [[1], [2], [3]]
n2 = [[1, 2, 3]]
matriz_mult(n1, n2) => True
  • This question already has an answer. Do a search. I’m on my cell phone and I have no way to find it now.

  • The memory may be failing me, but what you mean is, "...multiply in the order given"?

  • The problem begins by understanding the mathematical principle. What says that two matrix are multipliable?

  • If you already know the mathematical principle, read about the function len python.

  • @Wiker, sorry but I couldn’t locate, I had found something referring to the sum of matrices only. @A

2 answers

3


Mathematically, two matrices are multipliable if the number of columns of the first is equal to the number of rows of the second.

Whereas your matrices are in format:

n1 = [
  [1, 2, 3],
  [4, 5, 6]
]

Whereas n1 is a 2x3 matrix, we get the number of columns doing:

n1_cols = len(n1[0])

And you get the number of lines n2 making:

n2_rows = len(n2)

Just, then check the values are equal:

def matriz_mult(n1, n2):
    n1_cols = len(n1[0])
    n2_rows = len(n2)
    return (n1_cols == n2_rows)

See working on Repl.it.

  • Anderson your answer solves very simply with the use of "Len" Thanks!

1

In fact when you express:

n1 = [[1, 2, 3], [4, 5, 6]]
n2 = [[2, 3, 4], [5, 6, 7]]

You are just "representing" matrices, but in reality you are working with lists. In python, to work with true matrices Oce could use numpy. To solve what you propose I would make a function like this:

import numpy as np

def mult_array(n1, n2):
    m1 = np.array(n1)
    m2 = np.array(n2)
    try:
        dot(m1,m2)
        success = True
    except:
        success = False        
return success

Then you could call her:

print (mult_array(n1,n2))

Which would result in false, or

n3 = [[5,6,7,8][1,2,3],[9,8,7]]
print (mult_array(n1,n3)

Which would result: True.

  • Oops! So, I even tried using numpy, but the auto-fix program ends up generating error. Your idea is also valid, I should have specified that I could not use import. Thanks anyway!

  • @Nexus, when you say that the "automatic correction program ends up generating error", Voce means the editor? Do you have numpy installed? To find out try the following commands: python -c "import numpy; print(numpy.path)" or python -c "import numpy; print(numpy.version)" To install: Pip install numpy

  • no no, it is a program that performs correction even. So it ends up not being able to perform the import. I am aware of the commands.

Browser other questions tagged

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