Python矩阵,有解决方案吗? [英] Python matrix, any solution?

查看:97
本文介绍了Python矩阵,有解决方案吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的输入(例如):

from numpy import * 

x=[['1' '7']
 ['1.5' '8']
 ['2' '5.5']
 ['2' '9']]

我想在随机矩阵上做下一件事:

1.为每一行计算:

> for example first row:    [1;7]*[1,7] = [[1,  7];      #value * value.transpose
                                          [7,  49]]

> for example second row:   [1.5;8]*[1.5,8]=  [[2.25, 12];
                                               [12,  64]]
 >.......

这对于 numpy 很简单,因为如果x = [1,7],转置就是x.T 必须为矩阵上的每一行计算该值!

This is simple with numpy, because transpose is just x.T, if x=[1,7] This must be calculated for every row on matrix!

2.现在我想以此方式总结...

[1+2.25+...         7+12+......  ]
[                                ]           
[7+12+....          49+64+....   ]

结果就是这个矩阵.

有什么想法吗?

x=[['1','7']
 ['1.5', '8']
 ['2', '5.5']
 ['2','9']]

y = x[:, :, None] * x[:, None]
print y.sum(axis=0)

我收到错误:

列表索引必须是整数,而不是 元组"

"list indices must be integers, not tuple"

但是,如果x是x = numpy.array([[1, 7], [1.5, 8], [2, 5.5], [2, 9]]),那就可以了,但是我没有这样的输入.

But if x is x = numpy.array([[1, 7], [1.5, 8], [2, 5.5], [2, 9]]) then it's ok, but I don't have such input.

推荐答案

首先,您应该创建包含浮点数而不是字符串的矩阵:

First, you should create the matrix containing floating point numbers instead of strings:

x = numpy.array([[1, 7], [1.5, 8], [2, 5.5], [2, 9]])

接下来,您可以使用NumPy的广播规则进行构建产品矩阵:

Next, you can use NumPy's broadcasting rules to build the product matrices:

y = x[:, :, None] * x[:, None]

最后,对所有矩阵求和:

Finally, sum over all matrices:

print y.sum(axis=0)

打印

[[  11.25   48.  ]
 [  48.    224.25]]

请注意,此解决方案可避免任何Python循环.

Note that this solution avoids any Python loops.

这篇关于Python矩阵,有解决方案吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆