Could not broadcast input array from shape (1285) into shape (1285, 5334)
<p>I'm trying to follow some example code provided in the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.svd.html" rel="nofollow">documentation</a> for <code>np.linalg.svd</code> in order to compare term and document similarities following an SVD on a TDM matrix. Here's what I've got:</p>

<pre><code>results_t = np.linalg.svd(tdm_t)
results_t[1].shape
</code></pre>

<p>yields</p>

<pre><code>(1285,)
</code></pre>

<p>Also </p>

<pre><code>results_t[2].shape
(5334, 5334)
</code></pre>

<p>So then trying to broadcast these results to create a real <code>S</code> matrix per the classic SVD projection approach, I've got:</p>

<pre><code>S = np.zeros((results_t[0].shape[0], results_t[2].shape[0]), dtype = float)
S[:results_t[2].shape[0], :results_t[2].shape[0]] = results_t[1]
</code></pre>

<p>This last line produces the error:</p>

<pre><code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
&lt;ipython-input-329-16e79bc97c4b&gt; in &lt;module&gt;()
----&gt; 1 S[:results_t[2].shape[0], :results_t[2].shape[0]] = results_t[1]

ValueError: could not broadcast input array from shape (1285) into shape (1285,5334)
</code></pre>

<p>What am I doing wrong here?</p>

<p>You're using slicing when you should be using indexing. Take for example:</p>

<pre><code>A = np.zeros((4, 5))
end0, end1 = A.shape

# These are both true
A == A[:, :]
A[:, :] == A[:end0, :end1]

# To get the diagonal of an array you want to use range or np.arange
A[range(end0), range(end0)] == A.diagonal()
</code></pre>

<p>Some other things you might find useful:</p>

<pre><code># If U.shape is (a, b) and S.shape is (b,)
U.dot(np.diag(S)) == (U * S)

# IF V.shape (b, a) and S.shape is (b,)
np.diag(S).dot(V) == (S.reshape(b, 1) * V)
</code></pre>

python numpy svd