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>So according to the error message, the target </p>

<pre><code>S[:results_t[2].shape[0], :results_t[2].shape[0]]
</code></pre>

<p>is <code>(1285,5334)</code>, while the source</p>

<pre><code>results_t[1]
</code></pre>

<p>is <code>(1285,)</code>.</p>

<p>So it has to broadcast the source to a shape that matches the target before it can do the assignment.  Same would apply if trying to sum two arrays with these shapes, or multiply, etc.</p>

<ul>
<li><p>The first broadcasting step to make the number of dimensions match.  The source is 1d, so it needs to be 2d.  <code>numpy</code> will do try <code>results_t[1][np.newaxis,:]</code>, producing <code>(1, 1285)</code>.</p></li>
<li><p>Second step is to expand all size 1 dimensions to match the other.  But that can't happen here - hence the error. (1285,5334)+(1,1285)?</p></li>
</ul>

<p>======</p>

<p>If you want to assign to a block (or all of <code>S</code>) then use:</p>

<pre><code> S[:results_t[2].shape[0], :results_t[2].shape[0]] = results_t[1][:,np.newaxis]
</code></pre>

<p>To assign <code>r1</code> to a diagonal of <code>S</code>, use list indexing (instead of slices):</p>

<pre><code>S[range(results_t[1].shape[0]), range(results_t[1].shape[0])] = results_t[1]
</code></pre>

<p>or</p>

<pre><code>S[np.diag_indices(results_t[1].shape[0])] = results_t[1]
</code></pre>

<p>In this case those <code>ranges</code> have to match <code>results_t[1]</code> in length.</p>

python numpy svd