Skip to content

Instantly share code, notes, and snippets.

@nicolasfig
Created October 6, 2012 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicolasfig/3845547 to your computer and use it in GitHub Desktop.
Save nicolasfig/3845547 to your computer and use it in GitHub Desktop.
python: This file contains several matrix operations
#-------------------------------------------------------------------------------
# Name: Matrix
# Purpose:
#
# Author: Nicolas Figueroa
#
# Created: 06/10/2012
# Copyright: (c) Nicolas Figueroa 2012
#-------------------------------------------------------------------------------
import random
def fillMatrix(rows,cols):
'''(int, int) -> list[number]
Returns a matrix (list of lists) filled by the user with given rows and cols as
the matrix size
>>>fillMatrix(2,2)
Enter the [0][0] position of the matrix
1
Enter the [0][1] position of the matrix
2
Enter the [1][0] position of the matrix
3
Enter the [1][1] position of the matrix
4
[[1 , 2], [3 , 4]]
'''
matrix = []
for i in range(rows):
matrix.append([])
for j in range(cols):
matrix[i].append(int(input("Enter the [%d][%d] position of the matrix\n" % (i+1, j+1))))
return matrix
def randomMatrix(rows, cols, limit):
'''(int, int, int) -> list
Returns a random matrix with given rows and cols as the
matrix size and limit as the max number contained in the
matrix
>>> randomMatrix(2,2,10)
[[7, 0], [1, 9]]
>>> randomMatrix(3,3,13)
[[9, 10, 5], [1, 0, 3], [13, 9, 1]]
'''
matrix = []
for i in range(rows):
matrix.append([])
for j in range(cols):
matrix[i].append(random.randint(0,limit))
return matrix
def printMatrix(matrix):
'''(matrix) -> output
Prints a matrix, each rown in its own line to give readability
to the user
>>> printMatrix(matrix)
[[1, 2]]
[[3, 4]]
'''
for i in matrix:
print(i)
def multiplyMatrix(matrix1, matrix2):
'''(matrix, matrix) -> matrix
Returns a matrix multiplication between matrix1 and matrix2
if the matrix size (n*m m*p) is wrong prints a message.
>>>matrix1 = fillMatrix(2,2)
Enter the [0][0] position of the matrix
1
Enter the [0][1] position of the matrix
2
Enter the [1][0] position of the matrix
3
Enter the [1][1] position of the matrix
4
>>>matrix2 = fillMatrix(2,2)
Enter the [0][0] position of the matrix
1
Enter the [0][1] position of the matrix
2
Enter the [1][0] position of the matrix
3
Enter the [1][1] position of the matrix
4
>>> matrix3 = multiplyMatrix(matrix1, matrix2)
>>> print(matrix3)
[[12, 6]]
[[26, 16]]
'''
if len(matrix1) != len(matrix2[0]):
print("Wrong matrix size")
else:
result_matrix = []
for i in range(len(matrix1)):
list_a = []
for j in range(len(matrix2[0])):
s = 0
for k in range(len(matrix1[0])):
s += matrix1[i][k] * matrix2[k][j]
list_a.append(s)
result_matrix.append(list_a)
return result_matrix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment