Python Numpy : operands could not be broadcast together with shapes when producting matrix
<pre><code>import numpy as np
def grams(A):
    (m,n) = A.shape
    Q = A
    R = np.zeros((n,n))
    for i in range(0,n-1):
        R[i,i] = np.linalg.norm(Q[:,i])
        Q[:,i] =Q[:,i]/R[i,i]
        R[i,i+1:n] = np.transpose(Q[:,i])*Q[:,i+1:n]
        Q[:,i+1:n] = Q[:,i+1:n+1]-Q[:,i]*R[i,i+1:n]
    R[n,n] = np.linalg.norm(Q[:,n])
    Q[:,n] = Q[:,n]/R[n,n] 
    return Q, R
A = np.array( [[1,1,2],[4,3,1],[1,6,6]] )
print grams(A)
</code></pre>

<p>The error is on the line </p>

<pre><code>R[i,i+1:n] = np.transpose(Q[:,i])*Q[:,i+1:n]
</code></pre>

<p>The error is </p>

<pre><code>ValueError:
    operands could not be broadcast together with shapes (3,) (3,2) 
</code></pre>

<p>Asterisk <code>*</code> performs <strong>elementwise multiplication</strong> in <code>numpy</code>. Your code reads:</p>

<pre><code>R[i,i+1:n] = np.transpose(Q[:,i])*Q[:,i+1:n]
</code></pre>

<p><code>np.transpose(Q[:,i])</code> has dimensions <code>(3, 1)</code> and <code>Q[:,i+1:n]</code> <code>(3, 2)</code>, so they cannot be elementwise multiplied together as dimensions don't match.</p>

<p>I suspect you may want to multiply <code>np.transpose(Q[:,i])</code> and <code>Q[:,i+1:n]</code> using <strong>matrix multiplication</strong>, in that case you can use <code>numpy.dot</code> as follows:</p>

<pre><code>R[i,i+1:n] = np.dot(np.transpose(Q[:,i]), Q[:,i+1:n])
</code></pre>

<p>but dimensions don't match for matrix multiplication either, so your algorithm's implementation is probably wrong somewhere before that line.</p>

python numpy