0

I have question related to the code below. I found doing this operation quite frequent and would like to find a better way to do this. Perhaps there is a specific function or known technique to deal with this.

Problem: I have an array of 2D matrices (3D matrix) that needs to be applied some operation on per 2D matrix in this array.

My solution: Simply use for loop or comprehensions to loop through first dimension and aggregate the results into list.

Note: I am aware that A.append() here appends references and not copy. I have fixed this issue copy. This is yet another reason why I would like to find a better solution to this that does not mix numpy structures with Python native lists.

I am trying to do this operation

enter image description here

but on an array of X(big x) and corresponding array of x_hat in a verctorized numpy manner. I am looking for a clean 3D (or 2D) way to deal with 3D matrix multiplication like this.

P2_hat = np.ones((3,4)) #<-- [3, 4] X
pts3D_norm #<--------------- [n, 4]
x_hat #<---------------------[n, 2] x_hat

#Create null matrix for all 2D points
#-------------------minimum example of the operation
B = []
for i in range(n):
    null = np.array([[1.0 , 0.0, -x_hat[0, i]],
                     [0.0 , 1.0, -x_hat[1, i]]])
    B.append(null)
B = np.stack(B, axis=0)
#-------------------minimum example of the operation

A = []
for i in range(n):
    null = np.array([[1.0 , 0.0, -x_hat[0, i]],
                     [0.0 , 1.0, -x_hat[1, i]]])
    Ai = np.kron(null, pts3D_norm[:,i])
    omega = P_hat[2] @ pts3D_norm[:,i]
    Ai = Ai *  1 / omega
    A.append(Ai)
A = np.stack(A, axis=0) #<---------------Final [n, 2, 12]
Illia
  • 301
  • 1
  • 4
  • 16
  • I have no idea what the operation you are trying to do actually is. Can you create a minimum example. – blueteeth Mar 21 '20 at 17:44
  • @blueteeth I added B there. Please take a look. Essentially I am wondering if there is a vertorized way to do exactly that. Please let me know if you need more clarification. – Illia Mar 21 '20 at 17:59
  • `@` works with 'batches', the first of 3 dimensions (i.e. it does `dot` on the last 2 dimensions). `kron` is an `outer` product plus some transpose/reshape. So code that works with the whole 3d arrays is probably possible. But we need a clearer idea of what you are trying to do. What's the typical `n` size? – hpaulj Mar 21 '20 at 18:00
  • @hpaulj I added an image of exact operation my input is X, x_hat – Illia Mar 21 '20 at 18:07
  • In https://stackoverflow.com/questions/60383660/why-is-numpys-kron-so-fast/60386471#60386471 I try to explain what `np.kron` does. Notice how I use concrete examples, not symbolic images. – hpaulj Mar 21 '20 at 20:28

0 Answers0