开发者

multiply a matrix by an integer in python

I know how to multiply two matrices(under a class). Below I show my code. However I can not seem to figure out how to multiply a matrix and an integer in Python.

Update: Example 开发者_如何学JAVAof a matrix.

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.')


Depends on what you mean by matrix, but with numpy, it would be just like:

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]])

or

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜