Python Matrix, Any Solution?
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: > f
Solution 1:
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]])
Solution 2:
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.
Post a Comment for "Python Matrix, Any Solution?"