2

i have an array y with shape (n,), I want to compute the inner product matrix, which is a n * n matrix However, when I tried to do it in Python

np.dot(y , y) 

I got the answer n, this is not what I am looking for I have also tried:

np.dot(np.transpose(y),y) np.dot(y, np.transpose(y)) 

I always get the same answer n

2
  • Do note that the shape of x.T is the same as that of x. This is because x is a one-dimensional array. You want to use 2-d arrays. Try using np.reshape to make x 2 dimensional. Commented Oct 27, 2020 at 6:31
  • That dot is the inner product. The equivalent of np.sum(y*y), a scalar. To get a (70,70) you want the 'outer' product. Commented Oct 27, 2020 at 7:28

4 Answers 4

1

I think you are looking for:

np.multiply.outer(y,y) 

or equally:

y = y[None,:] y.T@y 

example:

y = np.array([1,2,3])[None,:] 

output:

#[[1 2 3] # [2 4 6] # [3 6 9]] 
Sign up to request clarification or add additional context in comments.

Comments

0

You can try to reshape y from shape (70,) to (70,1) before multiplying the 2 matrices.

# Reshape y = y.reshape(70,1) # Either below code would work y*y.T np.matmul(y,y.T) 

Comments

0

One-liner?

np.dot(a[:, None], a[None, :]) 

transpose doesn't work on 1-D arrays, because you need atleast two axes to 'swap' them. This solution adds a new axis to the array; in the first argument, it looks like a column vector and has two axes; in the second argument it still looks like a row vector but has two axes.

Comments

0

Looks like what you need is the @ matrix multiplication operator. dot method is only to compute dot product between vectors, what you want is matrix multiplication.

>>> a = np.random.rand(70, 1) >>> (a @ a.T).shape (70, 70) 

UPDATE:

Above answer is incorrect. dot does the same things if the array is 2D. See the docs here.

np.dot computes the dot product of two arrays. Specifically,

  • If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).
  • If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.

Simplest way to do what you want is to convert the vector to a matrix first using np.matrix and then using the @. Although, dot can also be used @ is better because conventionally dot is used for vectors and @ for matrices.

>>> a = np.random.rand(70) (70,) >>> a.shape >>> a = np.matrix(a).T >>> a.shape (70, 1) >>> (a @ a.T).shape (70, 70) 

2 Comments

dot does the same thing. Try it, and read the docs. (Your array is 2d, the OP's is 1d)
@hpaulj Good point. I will update my answer. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.