Home > Mobile >  How to Implement the Sparse matrix in python
How to Implement the Sparse matrix in python

Time:10-03

Hear I'm taking user input for matrix

print("Enter values for matrix ")
a = []
m = int(input("Number of rows, m = "))
n = int(input("Number of columns, n = "))

for i in range(m):
    l = []
    for j in range(n):
        l.append(int(input("Entry in row: {} column: {}\n".format(i 1,j 1))))
    a.append(l)

print("Matrix - =",a) 

if user input is Enter values for matrix Number of rows, m = 2 Number of columns, n = 3 Entry in row: 1 column: 1 1 Entry in row: 1 column: 2 2 Entry in row: 1 column: 3 3 Entry in row: 2 column: 1 4 Entry in row: 2 column: 2 5 Entry in row: 2 column: 3 6 Matrix - = [[1, 2, 3], [4, 5, 6]]

I'm trying to sparse Matrix to print Sparse Matrix: 001 012 023 104 115 126

CodePudding user response:

You need to add row, column values also to the 'l' variable and then reset it inside the second loop. Append 'l' should happen in second loop

print("Enter values for matrix ")
a = []
m = int(input("Number of rows, m = "))
n = int(input("Number of columns, n = "))

for i in range(m):
    for j in range(n):
        l = []
        l.append(i)
        l.append(j)
        l.append(int(input("Entry in row: {} column: {}\n".format(i 1,j 1))))
        a.append(l)

print("Matrix - =",a) 

output

Matrix - = [[0, 0, 1], [0, 1, 2], [0, 2, 3], [1, 0, 4], [1, 1, 5], [1, 2, 6]]

CodePudding user response:

To use the sparse matrix in python, simply install scipy library. Following is an example of how to use it with numpy.

# Load libraries
import numpy as np

from scipy import sparse

# Create a matrix
matrix = np.array([[0,0],[0,1],[3,0]])

# Create a compressed sparse row (CSR) matrix
matrix_sparse = sparse.csr_matrix(matrix)

# View sparse matrix 
print(matrix_sparse)

CodePudding user response:

Here's a better approach to get the matrix values.

rows, cols = map(int, input("Enter the number of rows and columns").split())
matrix = []

for i in range(rows):
    matrix.append(list(map(int, input("Enter the row values").split())))

for i in matrix:
    print(*i, sep="", end=" ")
  • Related