简体   繁体   中英

Create a matrix with user input dimension and numbers - Python

I'm trying to create two matrices by letting the user decide the dimensions and later choosing between inputting the numbers one by one or letting the system fill it in with random numbers. Later, the program should multiply both matrices and print the result.

This is what I have so far:

    import numpy as np
    print("Choose 4 numbers: ")
#Dimensions for the first matrix
    m = int(input("m: "))
    n = int(input("n: "))
#Dimensions for the second matrix
    m2 = int(input("m2: "))
    n2 = int(input("n2: "))
    mat = [0]
    mat=[(mat*n)]*m


    op = int(input("How would you like to arrange your matrix? For number by number press  1, \
     for random matrix press 2: "))



    if op == 1:
        for i in range(m):
            for j in range(n):
                num = int(input("Choose a number: "))
                mat[i][j] = num
        print (mat)

for x in range(m2):
            for y in range(n2):
                num2 = int(input("Choose a number: "))
                mat[x][y] = num2
        print (mat)

I have a couple of problems here. First, the first matrix is in linear form (example: "[[1,2,3],[4,5,6],[7,8,9]]"). Second, there seems to be an error with the second matrix: "IndexError: list assignment index out of range". For the random number fill, I know I can use np.matrix and np.random.

Thank you in advance!

Your code for the first matrix does correctly produce an n by m matrix, so this is be correct. The linear output [[0,0],[0,0]] is just how the matrix is displayed. However, you never make a second matrix. Make sure to initialize the second matrix too!

mat2=[([0]*n2)]*m2

Otherwise, you are indexing into the first matrix with the indices from the second matrix.

Also, as a note - you are using 2D lists to represent your matrices, for clarification purposes. numpy isn't required for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM