How to iterate using numpy instead of a for loop

Viewed 119

In the following code:

import numpy as np

a = np.array([1,3,5,7,9,11,13,15,17,19])
b = np.array([2,4,6,8,10,12,14,16,18,20])

c=0
for n in range(4,6):
    c+= a[9-n]*b[n]
print(c)

You can easily calculate c using a for loop. If I do the following instead of the for loop:

d =0
d+= np.dot(a[5:3],b[4:6])
print(d)

I get the error message:

shapes (0,) and (2,) not aligned: 0 (dim 0) != 2 (dim 0)

How do you alter the code to correct this?

3 Answers
d+= np.dot(a[5:3],b[4:6])

Look up the details of slicing. a[5:3] is an empty slice, so it doesn't match the required length for a dot-product. You need to specify a step of -1.

The dot error is telling us that your slices are wrong. One produces 0 values, and the other 2. dot requires matching sizes.

In [3]: a = np.array([1,3,5,7,9,11,13,15,17,19])
   ...: b = np.array([2,4,6,8,10,12,14,16,18,20])
   ...: 

Look at what values your loop index uses:

In [4]: for n in range(4,6):
   ...:     print(a[9-n], b[n])
   ...: 
11 10
9 12

Let's try to replicate them.

In [5]: idx = np.arange(4,6)
In [6]: idx
Out[6]: array([4, 5])
In [7]: a[9-idx], b[idx]
Out[7]: (array([11,  9]), array([10, 12]))

Or using slicing (with -1 step to step backwards):

In [8]: a[9-4:9-6:-1]
Out[8]: array([11,  9])
In [9]: b[4:6]
Out[9]: array([10, 12])

Now you can use the 2 slices in the dot.

my friend. as far as I can see in the error output, it emphasizes that the two NumPy arrays are not equal in size, because the expression you specify as a[5:3] is an empty slice . To fix this, you should do the following.

d =np.dot(a[4:6],b[4:6])

If you think I've misunderstood you, please warn me.

Related