Reputation: 249
How can I represent a column matrix and row matrix in python?
A =[1,2,3,4]
and
1
2
3
4
Upvotes: 1
Views: 17691
Reputation: 89765
Here is my implementation of matrix function that takes number of rows, columns and start value of the matrix
def matrix(rows, cols, start=0):
return [[c + start + r * cols for c in range(cols)] for r in range(rows)]
usage:
>>> m = matrix(5, 1)
>>> m
[[0], [1], [2], [3], [4]]
>>> m = matrix(3, 3, 10)
>>> m
[[10, 11, 12], [13, 14, 15], [16, 17, 18]]
Upvotes: 0
Reputation: 226734
Matrices are two dimensional structures. In plain Python, the most natural representation of a matrix is as a list of lists.
So, you can write a row matrix as:
[[1, 2, 3, 4]]
And write a column matrix as:
[[1],
[2],
[3],
[4]]
This extends nicely to m x n matrices as well:
[[10, 20],
[30, 40],
[50, 60]]
See matfunc.py for an example of how to develop a full matrix package in pure Python. The documentation for it is here.
And here is a worked-out example of doing matrix multiplication in plain python using a list-of-lists representation:
>>> from pprint import pprint
>>> def mmul(A, B):
nr_a, nc_a = len(A), len(A[0])
nr_b, nc_b = len(B), len(B[0])
if nc_a != nr_b:
raise ValueError('Mismatched rows and columns')
return [[sum(A[i][k] * B[k][j] for k in range(nc_a))
for j in range(nc_b)] for i in range(nr_a)]
>>> A = [[1, 2, 3, 4]]
>>> B = [[1],
[2],
[3],
[4]]
>>> pprint(mmul(A, B))
[[30]]
>>> pprint(mmul(B, A), width=20)
[[1, 2, 3, 4],
[2, 4, 6, 8],
[3, 6, 9, 12],
[4, 8, 12, 16]]
As another respondent mentioned, if you get serious about doing matrix work, it would behoove you to install numpy which has direct support for many matrix operations:
Upvotes: 5