Matrix Nxm (2D) in Python with Numpy

Asked

Viewed 1,043 times

0

I’m trying to solve a college activity, but I couldn’t transpose the logic into the code. The case is as follows: "The user will enter two integers. These integers will determine the size of the matrix. The user will pass the integers on the same line separated by space. After the user passes the values, the following values will be used as matrix data.

Ex.:

2 2
3 4
5 6

array will be ([3, 4], [5, 6])

i.e., a 2 x 2 matrix.

  • And what was the logic you thought? Could you describe it?

  • I understood what was asked, but my difficulty is just this, applying a logic to it.

  • Now that I looked at my question, I saw that I had put that I could not apply logic to the code, but in reality my problem is to create a logic to apply in the code...

5 answers

2


  1. You will need to read the user input in order to identify what will be the dimension of the matrix. Do this using the function input;

    a. The return of the function input will always be a string, then you’ll need to convert your string for a sequence of two integers. Do this with method support string.split and int;

  2. Having the matrix dimensions, Nxm, you will have to read N times the user input, which will be the matrix lines. Again use the function input to read the input and repeat the process with a repeat loop. I recommend doing with the structure for with support of the function range;

    a. Again, remember that the return of input will always be a string, then use the same logic of 1.a to convert it into a sequence of numbers;

Tips:

  1. A matrix can be represented as a list of lists;
  2. You can initialize an empty list like lista = [];
  3. You can add new elements in a list with lista.append(...);
  4. You can access a certain index in the list with lista[i];

Since you tried to do it, I’ll put an example in code:

import numpy

dimensions = input('Dimensões da matriz NxM: ').split()
N, M = [int(value) for value in dimensions]

matrix = []

for i in range(N):
    row = input(f'Linha {i+1}: ').split()

    if len(row) != M:
        raise Exception(f'Você precisa informar {M} valores por linha')

    numbers = [int(number) for number in row]
    matrix.append(numbers)

matrix = numpy.matrix(matrix)

print(matrix)

See working on Repl.it | Github GIST

An example of the generated output is:

>>> Dimensões da matriz NxM:  2 2
>>> Linha 1:  1 2
>>> Linha 2:  3 4
[[1 2]
 [3 4]]

0

So that, in case other people have the same problem, I’m putting the solution I created to my own problem that meets in 100% my case.

import numpy as np
dimensoes = input().strip().split()
N,M = (int(value) for value in dimensoes)
matriz = []
for i in range(N):
    if i < M:
        a = input().strip().split()
        matriz.append(list(map(int, a)))
    else:
        print("ERROR")
matriz = np.array(matriz)
print(matriz)
print(matriz.transpose())
print(matriz.flatten())
  • Why the condition i < M? There can be no 6x2 matrix, for example?

  • I am creating an Nxm matrix, if I is not less than M, taking into account that "i=0" and "M=0" for example, I will not be able to have a 2D matrix. After your placement, I saw that I would need to broaden the scope of my code to treat some treatments. Because of that, I have expanded my code, I will post a new answer.

  • But i will range from 0 to N-1. If N > M, it is certain that there will be the case of i > M. So I mentioned the example of 6x2, the value of i will vary from 0 to 5, while M is 2, but even so you will have a 2D matrix (6x2). That condition made no sense.

0

Follow new code with treatments:

import numpy as np
import sys
def mat(a):
    a1 = a
    a1 = list(map(int, a1))
    matriz.append(a1)
    return matriz

dimensoes = input().strip().split()
N,M = (int(value) for value in dimensoes)
matriz = []
saida = 0
for i in range(N):
    if saida == 1:
        break
    a = input().strip().split()
    if len(a) > M:
        print("Tamanho de N informado é maior que Dimensão inicial de N!")
        saida = 1
        break
    elif len(a) > N:
        print("Tamanho de M informado é maior que Dimensão inicial de M!")
        saida = 1
        break
    else:
        mat(a)
if saida == 0:
    matriz = np.array(matriz)
    print(np.transpose(matriz))
    print(matriz.flatten())

0

Good afternoon @Anderson!

Now the afternoon, I made the code after reading yours. Following my own logic, to learn more. The result of the code was the following:

import numpy as np
dimensoes = input().strip().split()
N,M = (int(value) for value in dimensoes)
matriz = []
for i in range(N):
    a = input().strip().split()
    if i < M:
        for j in range(M):
            a1 = a[j]
            a1 = (int(a1))
            matriz.append(a1)
    else:
        print("ERROR")   
matriz = np.array(matriz)
print(matriz)
print(np.transpose(matriz))
print(matriz.flatten())

the problem now is that the transpose() and Flatten() methods are not working as they should.

0

I managed to do this way, but it’s not using the list pattern I want, I need to use the numpy features.

import numpy as np
lista = []
matriz = input("Informe as dimensões da Matrix: ").strip().split()
N = int(matriz[0])
M = int(matriz[1])
for i in range(N-1):
    for j in range(M):
        a = input().strip().split()
        a1 = int(a[0])
        a2 = int(a[1])
        lista.append(a1)
        lista.append(a2)
print(lista)
  • Eric, since you demonstrated that you tried to do it, I added an example of what the code would look like in my answer. See if it meets you and any questions you may ask.

Browser other questions tagged

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