将矩阵的每一列都乘列索引的平方再求和 和 将矩阵的每一行都乘行索引的平方再求和

      为了解决 matlab 转过来的 Python 代码运行时间太长问题, 需要用到这个东西

     

1、将矩阵的每一列都乘列索引的平方再求和

      方法1

for i in range(row):
    for j in range(col):
        tempSum = tempSum + float(ngldm[i,j]) * ((j+1)**2)  # +1是因为下标从0开始

      方法2

for j in range(col):
    tempSum = np.sum(ngldm[:, j] * ((j + 1) ** 2)) + tempSum

      方法3

'''
    生成[[ 1 2 3 ... col]
        [ 1 2 3 ... col]
        ......
        [ 1 2 3 ... col]]的一个辅助矩阵,然后再按元素相乘
    '''
helpMatrix = np.tile((np.arange(1,col+1)),(row, 1))
tempSum = np.sum((np.multiply(ngldm, helpMatrix**2)))

     
方法3示例

app = np.array([[1,2,3],[4,5,6]])
bp = np.array([1,2,3])
cp  = np.tile(bp,(2,1))
np.multiply(app,cp)
array([[ 1,  4,  9],
       [ 4, 10, 18]])

     
     

2、将矩阵的每一行都乘行索引的平方再求和

      方法1

for i in range(row):
    for j in range(col):
        tempSum = tempSum + float(ngldm[i,j]) * ((i+1)**2)  # +1是因为下标从0开始

      方法2

for i iin range(row):
    tempSum = np.sum(ngldm[i, :,] * ((i + 1) ** 2)) + tempSum

      方法3

'''
    生成[[ 1 1 1 ... 1]
        [ 2 2 2 ... 2]
        ......
        [row row row ... row]]的一个辅助矩阵,然后再按元素相乘
    '''
helpMatrix = np.tile((np.arange(1,row+1)).reshape(-1,1),(1,col))
tempSum = np.sum((np.multiply(ngldm, helpMatrix**2)))  # np.multiply 是按元素相乘

      tile函数请看我的这篇文章 np.tile()函数的详解

     

方法3示例

app = np.array([[1,2,3],[4,5,6]])
bp = np.array([[1],[2]])   # 已经是一个列向量了
cp  = np.tile(bp,3)
np.multiply(app,cp)
array([[ 1,  2,  3],
       [ 8, 10, 12]])
posted on 2021-06-10 20:33  雾恋过往  阅读(198)  评论(0编辑  收藏  举报

Live2D