Aenaon
Aenaon

Reputation: 3573

Stacking a column vector and an array

Suppose I have a column vector

B = [[5], 
     [7]]

and an array

A = [[1, 1, 1, 1], 
     [247, 121, 1, 314]]

What I want to is to couple the top row of A with its counterpart from B (and similarly for the bottom ones) and then evaluate a function func(a,b) on these pairs. So for example if the function is the scipy.special.betaln I would like to calc the following

C = [[betaln(1,5)  , betaln(1,5)  , betaln(1,5), betaln(1,5)  ]
     [betaln(247,7), betaln(121,7), betaln(1,7), betaln(314,7)]]

which yields:

C = [[-1.609 , -1.609  , -1.609, -1.609 ]
     [-32.070, -27.1618, -1.945, -33.732]]

In reality I will have an array A with around 27,000 columns and rows anything from just a couple to a couple of hundreds. Hence, B will also be a vector of length 1 or two to a couple of hundreds. I have stuck on this and I dont know whats the best (fast) way to do it. I am doing that on tensorflow, thus A and B are tensors, but numpy arrays would also work just fine. (or maybe generators? I dunno...)

Thanks!

Upvotes: 0

Views: 69

Answers (1)

unutbu
unutbu

Reputation: 879611

scipy.special.betaln is a ufunc which means it can accept arrays (or in this case, even list-of-lists) as input. The values in A and B will be broadcasted for you automatically:

In [205]: special.betaln([[1, 1, 1, 1], [247, 121, 1, 314]], [[5], [7]])
Out[205]: 
array([[ -1.60943791,  -1.60943791,  -1.60943791,  -1.60943791],
       [-32.0707512 , -27.16180903,  -1.94591015, -33.73292188]])

Calling betaln once on the entire arrays will be much much faster than calling betaln multiple times -- once for each pair of scalar values.

Upvotes: 4

Related Questions