Nick - 1 year ago 84

Python Question

I have the following line of code in MATLAB which I am trying to convert to Python

`numpy`

`pred = traindata(:,2:257)*beta;`

In Python, I have:

`pred = traindata[ : , 1:257]*beta`

`beta`

In MATLAB,

`size(pred) = 1389 x 1`

But in Python,

`pred.shape = (1389L, 256L)`

So, I found out that multiplying by the

`beta`

How do I write the original Python line, so that the size of

`pred`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

I suspect that `beta`

is in fact a 1D `numpy`

array. In `numpy`

, 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 `beta`

vector to facilitate the multiplication. On top of this, the `*`

operator actually performs **element-wise** multiplication. To perform matrix-vector or matrix-matrix multiplication, you must use `numpy`

's `dot`

function to do so.

Therefore, you must do something like this:

```
import numpy as np # Just in case
pred = np.dot(traindata[:, 1:257], beta[:,None])
```

`beta[:,None]`

will create a 2D `numpy`

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 `beta`

, then you don't need to introduce the new singleton dimension. Just use `dot`

normally:

```
pred = np.dot(traindata[:, 1:257], beta)
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**