python矩阵每个元素加1,Python中矩阵元素的双重求和

Based on the simplified example below

d9367dbb4ed2468bd56664d21959e500.png

I would like in my code

from sympy import*

import numpy as np

init_printing()

x, y = symbols('x, y')

mat = Matrix([[x,1],[1,y]])

X = [1, 2, 3]

Y = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]

to substitute the symbolic x and y with values of X and Y and ofcourse calculate the double summation of the given matrix.

I'm trying to solve this but I'm having a rough time with the substitution in each step.

Any help would be highly appreciated.

解决方案

You've imported both SymPy and NumPy, so you have a choice of tools here. And for the job of adding together a bunch of numeric matrices, numpy is the right tool. Here is how the summation happens in numpy:

sum([sum([np.array([[x,1], [1,y]]) for y in yr]) for x, yr in zip(X,Y)])

Here yr stands for a row of elements of Y. The outer sum is over i index, the inner is over j, although the list comprehension eliminates the need to spell them out.

The result is a NumPy array:

array([[ 18, 9],

[ 9, 450]])

but you can turn it into a SymPy matrix just by putting Matrix() around it:

Matrix(sum([sum([np.array([[x,1], [1,y]]) for y in yr]) for x, yr in zip(X,Y)]))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值