What does this numpy code snippet do?
<pre><code>float(multiply(colVec1,colVec2).T * (matrix*matrix[i,:].T)) + c 
</code></pre>

<p>I am new to Python and numpy and I am trying to understand what the code snippet above does. </p>

<p>The <code>multiply().T</code> part performs an element-by-element multiplication and then does a transpose, and so the result becomes a row vector.  </p>

<p>I am trying to understand what <code>matrix[i,:]</code> does. Does it create a sub-matrix by picking just the i'th row vector or does it create a sub-matrix from the i'th row vector all the way to the end of the matrix?  </p>

<p>The <code>*</code> performs a dot-product which is then converted to a float using <code>float()</code>.  </p>

<p>Yes, <code>matrix[i, :]</code> will give you the i:th <strong>row</strong> of <code>matrix</code> since the <code>:</code> means "pick all in this dimension".</p>

<p>And no, <code>A * B</code> is not the dot product between <code>A</code> and <code>B</code>, it is the <strong>element-wise product</strong> of <code>A</code> and <code>B</code>.
To get the dot product you would use any of</p>

<pre><code>A.dot(B)
np.dot(A, B)
A @ B           # Python 3.5+ only
</code></pre>

<p>The above is true as long as you use the <code>np.ndarray</code> class, which you did if you created your matrices/arrays using <code>np.array</code>, <code>np.eye</code>, <code>np.zeros</code>, etc.
There is also a <code>np.matrix</code> class where the multiplication operator <code>*</code> is actually the dot product, but it is strongly adviced to <em>never</em> use it since it tends to create confusion when mixed with the normal array type.</p>

<h3>So what is going on in the expression?</h3>

<p>Lets's break it down to parts.</p>

<p><code>multiply(colVec1,colVec2).T</code> will create the transpose of the element-wise product of <code>colVec1</code> and <code>colVec2</code>.</p>

<p><code>matrix*matrix[i,:].T</code> is the element-wise product between <code>matrix</code> and the transpose of the i:th row of <code>matrix</code>. Due to numpys broadcasting rules this is actually the same as multiplying (elementwise) each row of <code>matrix</code> with its i:th row.</p>

<p>What we can see now is that both these expressions will create a matrix/array and not a scalar.
Therefore the call to <code>float()</code> will fail, as it expects a 1-element array or scalar.</p>

<p>My verdict is that someone has either been using the <code>np.matrix</code> class, or has interpreted the use of <code>*</code> wrong.</p>

python numpy matrix