user11812290
user11812290

Reputation:

How do I multiply a 1D array with only one other array in a 3D array?

I have a 1D array and I would like to multiply it with only the first axis of the 3D array.

For example, my 1D array has a length of 710, and I want to multiply it only with the first axis of the 3D array which also has a length of 710. I do not want it multiplied with the other two axes (because they are different sizes and I get an error).

How would I do that?

Below is the example code:

    data = sla_standard[:,:,:]
    window = w

    print(window.shape)
    print(data.shape)

    #GOAL: multiply the window with the first axis of my data array

    what is printed from console: 
    (710,)
    (710, 81, 320)

Upvotes: 2

Views: 92

Answers (1)

Marat
Marat

Reputation: 15738

Both arrays should have the same dimensionality (i.e. should be 3D). Once it is true, numpy will broadcast missing dimensions automatically (i.e., dimensions with only one row/column will be stretched to match the other array). Use window[:, None, None] to cast it to 3D:

>>> window = np.random.random((710))
>>> data = np.random.random((710, 81, 320))
>>> (window[:, None, None] * data).shape
(710, 81, 320)

Upvotes: 1

Related Questions