Matlab to Python numpy indexing and multiplication issue
<p>I have the following line of code in MATLAB  which I am trying to convert to Python <code>numpy</code>:</p>

<pre><code>pred = traindata(:,2:257)*beta;
</code></pre>

<p>In Python, I have:</p>

<pre><code>pred = traindata[ : , 1:257]*beta
</code></pre>

<p><code>beta</code> is a 256 x 1 array.  </p>

<p>In MATLAB,</p>

<pre><code>size(pred) = 1389 x 1
</code></pre>

<p>But in Python,</p>

<pre><code>pred.shape = (1389L, 256L)
</code></pre>

<p>So, I found out that multiplying by the <code>beta</code> array is producing the difference between the two arrays.  </p>

<p>How do I write the original Python line, so that the size of <code>pred</code> is 1389 x 1, like it is in MATLAB when I multiply by my beta array?</p>

<p>I suspect that <code>beta</code> is in fact a 1D <code>numpy</code> array.  In <code>numpy</code>, 1D arrays are not row or column vectors where MATLAB clearly makes this distinction.  These are simply 1D arrays agnostic of any shape.  If you must, you need to manually introduce a new singleton dimension to the <code>beta</code> vector to facilitate the multiplication.  On top of this, the <code>*</code> operator actually performs <strong>element-wise</strong> multiplication.  To perform matrix-vector or matrix-matrix multiplication, you must use <code>numpy</code>'s <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html"><code>dot</code></a> function to do so.</p>

<p>Therefore, you must do something like this:</p>

<pre><code>import numpy as np # Just in case

pred = np.dot(traindata[:, 1:257], beta[:,None])
</code></pre>

<p><code>beta[:,None]</code> will create a 2D <code>numpy</code> array where the elements from the 1D array are populated along the rows, effectively making a column vector (i.e. 256 x 1).  However, if you have already done this on <code>beta</code>, then you don't need to introduce the new singleton dimension.  Just use <code>dot</code> normally:</p>

<pre><code>pred = np.dot(traindata[:, 1:257], beta)
</code></pre>

python matlab numpy