Home > Back-end >  How to reshape matrix with numpy without using explicit values for argument?
How to reshape matrix with numpy without using explicit values for argument?

Time:11-05

I am trying to create a function and calculate the inner product using numpy. I got the function to work however I am using explicit numbers in my np.reshape function and I need to make it to use based on input.

my code looks like this:

import numpy as np
X = np.array([[1,2],[3,4]])
Z = np.array([[1,4],[2,5],[3,6]])

# Calculating S
def calculate_S(X, n, m):
    assert n == X.shape[0]
    n,d1=X.shape
    m,d2=X.shape
    S = np.diag(np.inner(X,X))
    return S


S= calculate_S(X,n,m)
S = S.reshape(2,1)
print(s)

output:
---------------------------------
[[ 5]
 [25]]

So the output is correct however instead of specifying 2,1 I need that those values to be automatically placed there based on the shape of my matrix. How do I do that?

CodePudding user response:

In [163]: X = np.array([[1,2],[3,4]])
In [164]: np.inner(X,X)
Out[164]: 
array([[ 5, 11],
       [11, 25]])
In [165]: np.diag(np.inner(X,X))
Out[165]: array([ 5, 25])

reshape with -1 gets around having to specify the 2:

In [166]: np.diag(np.inner(X,X)).reshape(-1,1)
Out[166]: 
array([[ 5],
       [25]])

another way of adding dimension:

In [167]: np.diag(np.inner(X,X))[:,None]
Out[167]: 
array([[ 5],
       [25]])

You can get the "diagonal" directly with:

In [175]: np.einsum('ij,ij->i',X,X)
Out[175]: array([ 5, 25])

another

In [177]: (X[:,None,:]@X[:,:,None])[:,0,:]
Out[177]: 
array([[ 5],
       [25]])
  • Related