1

How can I represent a column matrix and row matrix in python?

A =[1,2,3,4]

and

 1
 2
 3
 4
diva
  • 239
  • 1
  • 5
  • 13
  • It depends on what exactly you need, try to explain us why do you need this. List in python is always like row matrix but using different data types you can have what you need. – Artsiom Rudzenka Mar 28 '13 at 06:42
  • I have 2 matrices one row matrix and other column matrix.I want to multiply these two. – diva Mar 28 '13 at 06:45
  • Check this http://stackoverflow.com/questions/10508021/matrix-multiplication-in-python – Artsiom Rudzenka Mar 28 '13 at 06:47

2 Answers2

5

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:

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
  • 3
    Never too early to start. And honestly, I think that working with numpy arrays is going to be a whole lot easier than trying to replicate their functionality with lists. – mgilson Mar 28 '13 at 06:52
  • @RaymondHettinger I just found this answer, but the links in your answer are dead! – Victoria Aug 24 '17 at 11:03
0

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]]
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179