1

Pythonで列行列と行行列を表現するにはどうすればよいですか?

A =[1,2,3,4]

 1
 2
 3
 4
4

2 に答える 2

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:

于 2013-03-28T06:45:36.707 に答える