Reputation:
I get the following error ValueError: malformed string
when using the following code:
import numpy
l=[]
for x in [0.0,1.0]:
for y in [0.0,1.0]:
for z in [0.0,1.0]:
if x+y+z ==1:
print x
pr_matrix = numpy.matrix('x ; y ; z')
l.append(pr_matrix)
It seems to me that the numpy.matrix function is unable to understand that x,y,z are of type float and not of type string. I say so because the following works fine.
matrix = np.matrix('1 2 2;2 3 1')
Upvotes: 2
Views: 450
Reputation: 3106
Do not use numpy.matrix. It's deprecated and will be removed in the future NumPy releases. Instead you can use a simple comprehension
import itertools, numpy as np
arr=np.array([[[x],[y],[z]] for x,y,z in itertools.product(*[[1,0]]*3) if x+y+z==1])[:,:,0]
Here, itertools.product
is creating the cartesian product [0, 1]x[0, 1]x[0, 1]
which is what you do with 3 nested loops. To give this argument to the itertools.product
we basically first create three copies of [0,1]
in an iterable.
Then with a star argument (*
) before this iterable, we instruct to interpret the elements of this iterable as separate arguments so we get three distinct arguments. This produces the cartesian product
[(1, 1, 1),
(1, 1, 0),
(1, 0, 1),
(1, 0, 0),
(0, 1, 1),
(0, 1, 0),
(0, 0, 1),
(0, 0, 0)]
let's call this A
. Then we do a list comprehension over A. For each element in A
which is a 3-tuple x,y,z
we form a column and add it to the list created by the list comprehension if their sum is 1.
The result is then
[[[1], [0], [0]], [[0], [1], [0]], [[0], [0], [1]]]
and then an NumPy array is created but notice it is 3D. so we take the relevant part with a slice. You can also use np.squeeze
for this.
Upvotes: 2