1

With Numpy, I thought I could create a matrix this way

 z = np.array( [np.linspace(0, 1, 2), np.ones((1, 2)), np.ones((1, 2))] )

which, however, gives me:

array([array([ 0.,  1.]), array([[ 1.,  1.]]), array([[ 1.,  1.]])], dtype=object)

then checking its shape:

>>> z.shape
(3,)

The column dimension does not exist. So I think I got an array with three array objects.

How can I have the 3 x 2 matrix using linespace() and ones() here?

1
  • It was the mixed dimensions ( (2,) and (1,2)) that produced the 1d object array. Commented Mar 7, 2015 at 17:16

1 Answer 1

4

If the inputs are 1-dimensional, you could use numpy.array:

np.array([np.linspace(0, 1, 2), np.ones((2,)), np.ones((2,))])

yields

array([[ 0.,  1.],
       [ 1.,  1.],
       [ 1.,  1.]])

Note that np.ones((1,2)) has a 2-dimensional shape (1,2), while np.linspace(0, 1, 2) has a 1-dimensional shape (2,). To create the desired result with np.array, the arrays need to have compatible shapes -- in this case, that means using the 1-dimensional array np.ones(2,) instead of np.ones((1,2)).


If you must use np.ones((1,2)), then you could instead make np.linspace(0, 1, 2) 2-dimensional as well, and then use numpy.vstack:

np.vstack([np.linspace(0, 1, 2)[np.newaxis, :], np.ones((1,2,)), np.ones((1,2,))])

yields

array([[ 0.,  1.],
       [ 1.,  1.],
       [ 1.,  1.]])
Sign up to request clarification or add additional context in comments.

2 Comments

With compatible dimensions you don't even need vstack. Plain np.array works: np.array([np.linspace(0,1,2),np.ones((2,)),np.ones((2,))])
@hpaulj: Yes, I missed the easiest solution. Thanks for the improvement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.