2

Suppose I have two 1D arrays (a and b) and I want to sum them element-wise to create a 2D array (c). The 2D array has dimension (n,m) where n is the length of a and m is the length of b. The precise relation goes as: c[i][j] = a[i]+b[j], where i runs from 0 to n-1 and j runs from 0 to m-1. For example, consider the following code

a = np.asarray([1,2,3])
b = np.asarray([1,2])
c = a+b

This code gives me broadcasting error. The goal is to get c = [[2,3],[3,4],[4,5]]. Obviously we can use a loop to get every element of c, but I am looking for a way to do this without going through a loop.

2
  • Create a new axis. For (a + b).shape == (3, 2), we require that a.shape == (3, 1) and b.shape == (1, 2). Commented May 19, 2020 at 8:23
  • Can you write a short code that does this? Thanks! Commented May 19, 2020 at 8:27

2 Answers 2

2

For

(u + v).shape == (3, 2)

, we require:

u.shape == (3, 1)
v.shape == (1, 2)

Thus, the easiest way to accomplish this is by creating a new axis:

a = np.array([1, 2, 3])
b = np.array([1, 2])
c = a[..., np.newaxis] + b[np.newaxis, ...]
Sign up to request clarification or add additional context in comments.

2 Comments

I think it is useful to mention numpy broadcasting
I think this is working! Can you update your answer to the following code (for future reference)? a = np.asarray([1,2,3]) b = np.asarray([1,2]) c = a[:,np.newaxis]+b[np.newaxis,:] print(c)
0

Another way could be to tile your arrays using the length of the other array. Note that I take the transpose of np.tile(b, (len(a), 1)) with .T.

import numpy as np

a = np.asarray([1,2,3])
b = np.asarray([1,2])
c = np.tile(a, (len(b), 1)) + np.tile(b, (len(a), 1)).T

hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.