Matrix multiplication using slicing. Python
Question: I have the following code:

    
    
    from numpy import *
    a = random.rand(3,4)
    b = random.rand(4,2)
    c = linspace(0,0,6)
    c.shape = (3,2)
    for i in range(a.shape[0]): 
      for j in range(b.shape[1]): 
          for k in range(b.shape[0]): 
             c[i][j] += a[i][k] * b[k][j]
    for r in c: 
      print "C = ", r
    

But I need to change the last (innermost) loop and I need to use slicing. As I
understood I have to do something like this:

    
    
    for i in range(a.shape[0]): 
     for j in range(b.shape[1]): 
         c[i][j] += a[i][0:l-1] * b[0:l-1][j]
    

But, unfortunately, it doesn't work. Could somebody help me and give a hint
how to do it?


Answer: What you're trying to do here is the dot product of the row vector from `a`,
and the column vector from `b`:

    
    
    c[i][j] += a[i][0:l-1] * b[0:l-1][j]
    

which would be

    
    
    c[i][j] = np.dot(a[i], b[:][j]) 
    

which is the same as

    
    
    sum([a_*b_ for a_,b_ in zip(a[i],b[:][j])])
    

or

    
    
    sum(a[i]*b[:][j])
    

but faster.

However, if you're using `np.dot`, anyways:

    
    
    c = np.dot(a,b)
    

is definitely faster.

