这是一个问题:您需要一个算法,该算法向用户询问方形矩阵的行数,然后用计数整数填充矩阵的上三角。您的矩阵应该是一个2D Numpy数组。
注:
由于矩阵大小为正方形,行数和列数相同,因此可以从使用适当的numpy方法将矩阵初始化为所有零条目开始,您的算法应该用于循环。
在循环中,一条消息应该显示当前的行和列索引以及要存储在该位置的值。
循环完成后,应显示整个矩阵您的算法将提示用户输入矩阵大小,并适应输入的大小
提示:如果你很难完成这项任务,可以把它分解成更容易的类似任务。
这些可能是:
- 用值1填充整个矩阵(在循环中(
- 打印一个正方形矩阵,其中整个矩阵都填充了递增的整数
完成这些任务后,您可能会对如何解决此问题中的任务有更好的想法。
这是我的代码:
#input size of matrix from the user
M = int(input('Enter Matrix size: '))
N = M
#The dimension of the matrix in nXm
dimension = (M, N)
#form a matrix of size nXm
matrix = np.zeros(dimension, dtype=int)
#use the num for filling the values in the matrix
num = 1
#for every row
for i in range (M):
#the elements before the diagonal are 0
for j in range (i+1):
#print ("The value at row " + str(i) + " and column " + str(j) + " is 0", end = 'n')
#the elements after the diagonal are num
for j in range (i,N):
#print ("The value at row " + str(i) + " and column " + str(j) + " is " + str(num), end = 'n')
matrix[i][j] = num
#increase num by 1
num = num + 1
#print the upper triangular matrix
print (matrix)
它打印的矩阵是:[1,1,10、3、30,0,6]
我想打印的矩阵是:[1,2,30、4、50,0,6]
我认为您想要生成一个上三角方形矩阵。
import numpy as np
#input size of matrix from the user
n = int(input('Enter Matrix size: '))
#form a matrix of size nXn
matrix = np.zeros((n,n), dtype=int)
#use the num for filling the values in the matrix
num = 1
for i in range(n):
#the elements before the diagonal are 0
for j in range(i):
print (f"The value at row {i} and column {j} is 0")
for j in range (i, n):
print (f"The value at row {i} and column {j} is {num}")
matrix[i][j] = num
num = num + 1
print (f"matrix=n{matrix}")
n=4
的输出
Enter Matrix size: 4
The value at row 0 and column 0 is 1
The value at row 0 and column 1 is 2
The value at row 0 and column 2 is 3
The value at row 0 and column 3 is 4
The value at row 1 and column 0 is 0
The value at row 1 and column 1 is 5
The value at row 1 and column 2 is 6
The value at row 1 and column 3 is 7
The value at row 2 and column 0 is 0
The value at row 2 and column 1 is 0
The value at row 2 and column 2 is 8
The value at row 2 and column 3 is 9
The value at row 3 and column 0 is 0
The value at row 3 and column 1 is 0
The value at row 3 and column 2 is 0
The value at row 3 and column 3 is 10
matrix=
[[ 1 2 3 4]
[ 0 5 6 7]
[ 0 0 8 9]
[ 0 0 0 10]]