Making a Matrix in Python 3 Without Numpy Using Inputs

Making a matrix in python 3 without numpy using inputs

If your objective is only to get the output in that format

n,m=map(int,input().split())
count=0
for _ in range(0,n):
list=[]
while len(list) > 0 : list.pop()
for i in range(count,count+m):
list.append(i)
count+=1
print(list)

how to display 3 * 3 matrix in python without Numpy function

The answer to your question is the same as this answer:

L = [1,2,3,4,5,6,7,8,9]
L = [L[i:i+3] for i in range(0, len(L), 3)]
print(L)

Output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

How can I create a Triadiagonal Matrix on Python, without numpy and with user's input?

Thanks @PharaohOfParis.
I've changed your code a little. Now it works perfect!

def tridiagonal(n):
values1 = []
values2 = [0]
print("Enter R values ")
for i in range(0, n):
values1.append(float(input()))

for i in range(0, n):
values2.append(values1[i])

print(values1)
print(values2)

M = [ [0 for j in range(n)] for i in range(n) ]
for k in range(n-1):
M[k][k] =values1[k]+values2[k]
M[k][k+1] = -values1[k+1]
M[k+1][k]= -values1[k+1]
M[n-1][n-1]= values1[n-1]+values2[n-1]
print(M)

tridiagonal(5)

How can I make this matrix in python without using numpy?

Use list comprehension:

N = 4
>>> [[N-i]*(i+1)+[0]*(N-i-1) for i in range(N)]
[[4, 0, 0, 0], [3, 3, 0, 0], [2, 2, 2, 0], [1, 1, 1, 1]]

In a function:

def fill_matrix(N):
return [[N-i]*(i+1)+[0]*(N-i-1) for i in range(N)]

def print_matrix(m):
print("\n".join(["\t".join(map(str, row)) for row in m]))

>>> fill_matrix(6)
[[6, 0, 0, 0, 0, 0],
[5, 5, 0, 0, 0, 0],
[4, 4, 4, 0, 0, 0],
[3, 3, 3, 3, 0, 0],
[2, 2, 2, 2, 2, 0],
[1, 1, 1, 1, 1, 1]]

>>> print_matrix(fill_matrix(6))
6 0 0 0 0 0
5 5 0 0 0 0
4 4 4 0 0 0
3 3 3 3 0 0
2 2 2 2 2 0
1 1 1 1 1 1

The ith row consists of:

  1. The number N-i repeated i+1 times
  2. 0 repeated N-(i+1) times

Matrix power without Numpy for 3x3 Matrix

If the power argument is really huge, then use an iterative solution, by iterating the binary bits of the power:

def matpow(mat, p):
# Start with the identity matrix. This way it will also work for p==0
# If you are using floats, then make this also with floats:
result = [[1,0,0],[0,1,0],[0,0,1]]
while p > 0:
if p & 1:
result = matmul(result, mat)
mat = matmul(mat, mat)
p >>= 1
return result


Related Topics



Leave a reply



Submit