0

I am trying to do some linear combination of numpy arrays.

I have three lists of numpy arrays:

a = [np.random.normal(0,1, [1,2]), np.random.normal(0,1, [3,4]), np.random.normal(0,1, [10,11])] b = [np.random.normal(0,1, [1,2]), np.random.normal(0,1, [3,4]), np.random.normal(0,1, [10,11])] c = [np.random.normal(0,1, [1,2]), np.random.normal(0,1, [3,4]), np.random.normal(0,1, [10,11])]

I want to element-wise combine each element in each array in list a and b based on corresponding element's value of c , to get a new list d: say d_i = a_i * c_i + (1-c_i) *b_i(linear combination).

What I thought was to pick each element in each array in a and find corresponding elements in b and c and then combine. However, I found this is troublesome, inefficient and a bit stupid. Could anyone suggest a better way?

3
  • 2
    I don't understand what you are trying to do Commented Nov 29, 2017 at 23:10
  • Added d_i = a_i * c_i + (1-c_i) *b_i, where each variable denotes each element in each array in list. Commented Nov 29, 2017 at 23:12
  • Why do you have lists of arrays? Commented Nov 29, 2017 at 23:20

1 Answer 1

1

Well assuming all of your lists are the same length then I don't think that there is going to be anything much more efficient than

d = [a[i] * c[i] + (1-c[i]) * b[i] for i in range(len(a))]

Now if all you need to do is operate upon the list d one time then maybe you could speed things up with a generator comprehension?

d = (a[i] * c[i] + (1-c[i]) * b[i] for i in range(len(a)))

But at the end of the day there is no way to create a linear combination of elements in less than linear time.

Sign up to request clarification or add additional context in comments.

7 Comments

Ideally a list comprehension is the most efficient for creating a list. However, as you say if you have further operations, it's good to defer list creation.
Wow, you are clever!
@xaav I can update to use a list comprehension, but a generator comprehension is truly the most efficient as it doesn't save anything unnecessarily if the list is only being traversed once.
You reminds me d = [], for x, y, z in zip(a,b, c): d.append(z*x + (1-z) *y), could anyone comments on this way?
It depends what y'all mean by "efficient". List comprehensions are marginally faster than equivalent for-loops at constructing lists. If you don't actually need a list, and merely need to process each element, then a generator-expression or some form of lazy-iterable would be ideal.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.