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>(note, looking at Bi Rico's answer, it looks like perhaps the right interpretation was that you aren't actually trying to broadcast with that command?  This answer shows how to actually do the broadcasting.)</p>

<pre><code>X = scipy.zeros((5,4))
X
&gt; array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])

Y = scipy.arange(5)
Y
&gt; array([0, 1, 2, 3, 4])
X[:,:]=Y
&gt; could not broadcast input array from shape (5) into shape (5,4)
</code></pre>

<p>So instead try</p>

<pre><code>X[:,:]=Y[:,None]
X
&gt; array([[ 0.,  0.,  0.,  0.],
   [ 1.,  1.,  1.,  1.],
   [ 2.,  2.,  2.,  2.],
   [ 3.,  3.,  3.,  3.],
   [ 4.,  4.,  4.,  4.]])
</code></pre>

<p>You can get a bit more understanding of the issue from the following</p>

<pre><code>Z = scipy.arange(4)
Z
&gt; array([0, 1, 2, 3])
X[:,:]=Z
X
&gt;array([[ 0.,  1.,  2.,  3.],
       [ 0.,  1.,  2.,  3.],
       [ 0.,  1.,  2.,  3.],
       [ 0.,  1.,  2.,  3.],
       [ 0.,  1.,  2.,  3.]])
</code></pre>

<p>The issue here is that it's convinced you're treating <code>Y</code> (or <code>Z</code>) as a row of the array, while you're trying to fit it into a column.  Doing <code>Y[:,None]</code> basically forces it to interpret Y as a column.</p>

python numpy svd