在Python中将矩阵乘以整数

时间:2011-04-03 16:15:30

标签: python

我知道如何将两个矩阵相乘(在一个类下)。下面我展示我的代码。但是,我似乎无法弄清楚如何在Python中乘以矩阵和整数。

更新: 矩阵的例子。

L=[[1,2],[3,4],[5,6]]
3*L
# [[1,6],[9,12],[15,18]]

def __mul__(self,other):
    '''this will multiply two predefined matrices where the number of
    columns in the first is equal to the number of rows in the second.'''
    L=self.L
    L2=other.L
    result=[]
    if len(L[0])==len(L2):
        for i in range(len(L)):
            row=[]
            for j in range(len(L2[0])):
                var=0 
                for k in range(len(L2)):
                    var=var+L[i][k]*L2[k][j]
                row=row+[var]
            result = result+[row]
        return matrix(result)
    else:
        raise ValueError('You may not only multiply m*n * n*q matrices.')

2 个答案:

答案 0 :(得分:4)

取决于matrix的含义,但numpy取决于:

import numpy as np

M= np.arange(9).reshape(3, 3)
# array([[0, 1, 2],
#        [3, 4, 5],
#        [6, 7, 8]])
2* M
# array([[ 0,  2,  4],
#        [ 6,  8, 10],
#        [12, 14, 16]])

M= np.matrix([[1, 2], [3, 4]])
# matrix([[1, 2],
#         [3, 4]])
2* M
# matrix([[2, 4],
#         [6, 8]])

答案 1 :(得分:0)

L=[[1,2],[3,4],[5,6]]
[[elem*3 for elem in row] for row in L]
[[3, 6], [9, 12], [15, 18]]