Python matrix, any solution? [duplicate]
MY input(just for example):
from numpy import *
x=[['1' '7']
['1.5' '8']
['2' '5.5']
['2' '9']]
I want to make next thing on random matrix:
1. for each row calculate:
> 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]]
>.......
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. now I want to sum as in this way...
[1+2.25+... 7+12+...... ] [ ] [7+12+.... 49+64+.... ]
So result is this matrix.
Any ideas?
EDIT2:
x=[['1','7']
['1.5', '8']
['2', '5.5']
['2','9']]
y = x[:, :, None] * x[:, None]
print y.sum(axis=0)
I received error:
"list indices must be integers, not tuple"
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.
How about the following:
In [1]: import numpy as np
In [2]: x=np.array([[1, 7],[1.5, 8],[2, 5.5],[2, 9]])
In [3]: np.sum(np.outer(row,row) for row in x)
Out[3]:
array([[ 11.25, 48. ],
[ 48. , 224.25]])
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]])
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)
printing
[[ 11.25 48. ]
[ 48. 224.25]]
Note that this solution avoids any Python loops.
精彩评论