-1

I have an empty numpy array (let's call it a), which is for example (1200, 1000) in size.

There are several numpy arrays that I want to get sum of them and save them in the array a.

The size of these arrays (b_i) are like (1200, y), and y is max=1000.

Simply writing a code such as:

a = a + b_i

didn't work because of second dimension mismatch.

How can I solve that?

Kadaj13
  • 1,423
  • 3
  • 17
  • 41
  • You can't sum up arrays with mismatching dimensions. Are you looking at concatenating them maybe? – NotAName May 23 '22 at 00:47
  • What does "didn't work" mean? Did you get an error? If so what was the error? – Code-Apprentice May 23 '22 at 00:49
  • 1
    Please show a small example of what inputs might look like, and what output you expect. Your account is over 9 years old and you have multiple questions asked this year, so you should know well how this works by now, but: When something "didn't work", please explain exactly what that entails. If the output was wrong, show the wrong output, and explain how it is different from the expected output. If there was an error message, show a [complete](https://meta.stackoverflow.com/questions/359146/) error message, formatted like code. – Karl Knechtel May 23 '22 at 00:52
  • What is it supposed to do with the dimensions don't match? Don't assume that `numpy` operates with the same logic or intuition that you have. – hpaulj May 23 '22 at 00:52
  • have you tried to pad numpy array with zeros? – blackraven May 23 '22 at 00:57

2 Answers2

1

The only idea I have with this is to start taking a sub-array of a with dimensions matching the b_i array and adding it that way. So something like this:

import numpy as np

a = np.zeros((12, 10))
b_1 = np.random.randint(1, 10, size=(12, 5))
b_2 = np.random.randint(1, 10, size=(12, 7))
b_3 = np.random.randint(1, 10, size=(12, 9))
arrs = [b_1, b_2, b_3]

for arr in arrs:
    a[:, :arr.shape[1]] += arr

Or alternatively, as @BlackRaven had suggested you could instead pad the b_i with zeros to get it to the same shape as a.

NotAName
  • 3,821
  • 2
  • 29
  • 44
1

If you just want to concatinate arrays:

a = np.ones((1200,1000))
b = np.ones((1200, 500))
c = np.concatenate((a, b), axis=1)
c.shape # == (1200, 1500)

If you want elementwise addition, then reshape b to have the same dimentions as a

a = np.ones((1200,1000))
b = np.ones((1200, 500))
b_pad = np.zeros(a.shape)
b_pad[:b.shape[0],:b.shape[1]] = b
a + b_pad
array([[2., 2., 2., ..., 1., 1., 1.],
       [2., 2., 2., ..., 1., 1., 1.],
       [2., 2., 2., ..., 1., 1., 1.],
       ...,
       [2., 2., 2., ..., 1., 1., 1.],
       [2., 2., 2., ..., 1., 1., 1.],
       [2., 2., 2., ..., 1., 1., 1.]])

If you want a reusable function for this, then have a look at this question

James McGuigan
  • 7,542
  • 4
  • 26
  • 29
  • Numpy has a [pad function](https://numpy.org/doc/stable/reference/generated/numpy.pad.html): `a + np.pad(b, a.shape[0])`. – mins May 02 '23 at 08:57