0
votes

I am trying to do a matrix multiplication with two numpy arrays, one is a 2x2 and the other I want to treat as a 2x1, but there is a third dimension due to a linspace variable. This makes it not possible to apply the transformation as I intend

The code:

import numpy as np 
t = 0
delt = 0
theta = 0
n = np.linspace(0,1,0.1)
E_z = np.exp((t - n) * 1j)
E_y = np.exp((t - n - delt) * 1j)
QW = np.array([[np.cos(theta)**2 + 1j * np.sin(theta)**2, (1 - 1j) * np.sin(theta) * np.cos(theta)], 
                  [1j * np.cos(theta)**2 + np.sin(theta)**2, (1 - 1j) * np.sin(theta) * np.cos(theta)]])
QW = np.multiply(QW, np.exp(-(pi/4) * 1j))
E = np.array([[E_y],[E_z]])
E = np.dot(QW, E)

The error received is

"ValueError: shapes (2,2) and (2,1,14) not aligned: 2 (dim 1) != 1 (dim 1)"

Thanks for the help!

2
we can't run your code because you have self, t etc in it. It's also unclear as to what you're trying to achieve - Rocky Li
The error is probably produced by the last line, the dot. That function expects the last dim of QW to match the 2nd to the last of E. Are those the expected dimensions for those variables? You should have a clear idea of what array dimensions are at each step. Print shape periodically to verify your intuitions. Test pieces interactively if needed. - hpaulj
@RockyLi, sorry, was moving from my code to here, put in values for the variables, sorry bout that - Cade
@hpaulj Is there a better function to use then? - Cade
Do you want that E to be (2,1) or (2,14)? - hpaulj

2 Answers

0
votes

The problem with the code is in the line

E = np.array([[E_y],[E_z]])

This tells numpy that you want to stack 2 10 x 1 arrays hence yielding the 2 x 1 x 10. Leaving out the inner-brackets yields a 2 x 10 array. For future reference, the .squeeze method can be used to remove inner 1 dimensions.

import numpy as np 
t = 0
delt = 0
theta = 0
n = np.arange(0,1,0.1)
E_z = np.exp((t - n) * 1j)
E_y = np.exp((t - n - delt) * 1j)
QW = np.array([[np.cos(theta)**2 + 1j * np.sin(theta)**2, (1 - 1j) * np.sin(theta) * np.cos(theta)], 
                  [1j * np.cos(theta)**2 + np.sin(theta)**2, (1 - 1j) * np.sin(theta) * np.cos(theta)]])
QW = np.multiply(QW, np.exp(-(np.pi/4) * 1j))
E = np.array([E_y,E_z])
E = np.dot(QW, E)
0
votes

the QW dimension caused the problem you can try this

QW = np.multiply(QW, np.exp(-(pi/4) * 1j)).reshape(2,2,1)