Devansh Agarwal
Devansh Agarwal

Reputation: 126

Multiple dimension matrix multiplication in Python

I have a matrix M, M.shape = (4, 4) and M[1,1].shape=(600,300). Each M[i,j] is calculated by passing a meshgrid. For Example

x=300
t=np.linspace(0, np.pi, num=x)
p=np.linspace(0,2*np.pi,num=2*x)
[T,P]=np.meshgrid(t,p)
M[1,1]=np.sin(T)*np.cos(P)

Each element of M is a different combination of sin and cos.

Next I have x, such that x.shape=(4, 600, 300). x is calculated as follows:

for j in xrange(n):
    x[0]+=np.sin(T)*np.sin(time[j])
    x[1]+=np.sin(T)*np.sin(time[j])
    x[2]+=np.sin(P)*np.cos(time[j])
    x[3]+=np.sin(P)*np.cos(time[j])

where time[j] is some number.

I want to know how to compute transpose(x).M.X. So this should come to be a quantity of shape(600,300). I have computed a = np.tensordot(M,x,axes=[1,0]) which yields a.shape=(4,600,300).

Firstly, is this correct? Secondly. I how to take the transpose and compute transpose(x).M.x?

Upvotes: 1

Views: 144

Answers (1)

hpaulj
hpaulj

Reputation: 231655

Forget about how you calculate things like M and x, and focus on the multiplication:

I want to know how to compute transpose(x).M.X. So this should come to be a quantity of shape(600,300). I have computed a = np.tensordot(Mat,x,axes=[1,0]) which yields a.shape=(4,600,300).

What is the total shape of M? wwiis guess makes most sense (4,4,600,300).

You say x is (4, 600,300). What is transpose(x)? Transpose is defined for 2 axes, but ambiguous with 3.

What is X?

what is Mat? The only thing that works in your np.tensordot(Mat,x,[1,0]) is (4,4).

But let me make an educated guess, you want X.T * M * X, but with the added (600,300) dimension.

 np.einsum('inm,ijnm,jnm->nm', X, M, X)

That is, you want a dot produce of X with the 1st dim of M, and another dot product of X with the 2nd dim of M, without altering the last 2 dimensions.

Upvotes: 1

Related Questions