Home > Mobile >  How can I make a column vector?
How can I make a column vector?

Time:06-04

I'm trying to convert my MATLAB code to Python. In MATLAB I wrote:

G=[x(:).^0 x(:).^1];

Where x size is (1,2001) and created by

x=linspace(-10,10,2001)

G size is (2001,2) the first column is equal to 1, and the second column the value of x.

When I try to make the G matrix

G=np.array([[x.T**0],[x.T**1]])

it creates an array of size (2,1,1,2001).

I've tried

G=np.array((np.ones(x.size).T, x.T))

But that's not the way I want it. How can it be fixed?

CodePudding user response:

While everything is MATLAB is 2d (or larger), and the trailing dimension is outer most, in numpy arrays can be 1d (or even 0d), and the leading dimension is outer most.

In [208]: x = np.linspace(-10,10,5)

In [209]: x
Out[209]: array([-10.,  -5.,   0.,   5.,  10.])     
In [210]: x.shape
Out[210]: (5,)

Transpose does nothing to a 1d array:

In [211]: x.T
Out[211]: array([-10.,  -5.,   0.,   5.,  10.])

np.array is a natural tool for combining arrays of matching size. That's just an extension of the common demo, np.array([[1,2],[3,4]]) where the argument is a list of 2 lists.

In [212]: np.array((x**0, x**1))
Out[212]: 
array([[  1.,   1.,   1.,   1.,   1.],
       [-10.,  -5.,   0.,   5.,  10.]])

I would argue that such an array (2,n) is the natural translation of a MATLAB (n,2) matrix.

But such a array can be easily transposed:

In [213]: np.array((x**0, x**1)).T
Out[213]: 
array([[  1., -10.],
       [  1.,  -5.],
       [  1.,   0.],
       [  1.,   5.],
       [  1.,  10.]])

Or you could use stack with axis:

In [214]: np.stack((x**0, x**1), axis=1)
Out[214]: 
array([[  1., -10.],
       [  1.,  -5.],
       [  1.,   0.],
       [  1.,   5.],
       [  1.,  10.]])

You could make a 2d array, shape (5,1) with:

In [216]: x1 = x[:,None]   # or x.reshape(-1,1)

In [217]: x1
Out[217]: 
array([[-10.],
       [ -5.],
       [  0.],
       [  5.],
       [ 10.]])

This is closer to what MATLAB users would call a column vector.

Then concatenate those on the 2nd axis:

In [218]: np.hstack((x1**0, x1**1))
Out[218]: 
array([[  1., -10.],
       [  1.,  -5.],
       [  1.,   0.],
       [  1.,   5.],
       [  1.,  10.]])

Seems that wayward MATLAB users often have a hard time getting used to the differences (and commonalities) of (n,), (1,n) and (n,1) shaped arrays. :)

CodePudding user response:

To make G you need to use numpy.vstack:

import numpy as np

x1 = np.linspace(-10, 10, 2001)
x0 = x1**0

G = np.vstack((x0,x1)).T
print(G.shape)

(2001, 2)

  • Related