Matrix MxN, fill vector with matrix values.

0
import random
n = int(input("Ingrese el numero de fila: \n"))
m = int(input("Ingrese el numero de columna: \n"))
#a = n*m
matriz = []

for i in range(n):  
    for j in range(m):
        matriz[i][j] = random.randint(0, 100)
 print(matriz)

I have this way of creating a matrix but I get this error:

matriz[i][j] = random.randint(0, 100)

IndexError: list index out of range

    
asked by Daniel Alzate 28.04.2018 в 04:48
source

3 answers

1

You can do it first install numpy

pip install numpy

Then:

# -*- coding: utf-8 -*-

import numpy as np

n = int(input("Ingrese el numero de fila: \n"))
m = int(input("Ingrese el numero de columna: \n"))

matriz = np.random.randint(0, 100, size=(n, m))
print(matriz)
    
answered by 28.04.2018 в 05:08
1

You have to use append to define the matrix and assign its values to it. For example:

import random
n = 4
m = 3
#a = n*m
matriz = []

for i in range(n):
    matriz.append([])
    for j in range(m):
        matriz[i].append(random.randint(0, 100))

print(matriz)

Exit:

$python main.py
[[7, 78, 57], [18, 3, 58], [30, 44, 17], [45, 39, 64]]

In this way, you are adding to the matrix the number of rows with the first for ( matriz.append([]) ), and then you are adding the elements of the columns with the second for ( matriz[i].append(elemento) ). It's a summary, first you have to add row by row, and then, for each row added, you add the elements of the columns.

    
answered by 28.04.2018 в 05:44
0

It will be out of range because the variable matrix is an empty list, if you say matrix [0] [0] it is not defined unless it is a list of lists.

One way to create an array is this:

import random
a=[]
filas=5
columnas=4
for i in range(filas):
    a.append([])
    for j in range(columnas):
        a[i].append(random.randrange(100))

print(a)

But there is a more compact and practical way to create a matrix:

a=[[i for i in range(6)]for j in range(4)]

whose result is this:

[[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]]
    
answered by 28.04.2018 в 16:50