Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

python - numpy array creating with a sequence

I am on my transitional trip from MATLAB to scipy(+numpy)+matplotlib. I keep having issues when implementing some things. I want to create a simple vector array in three different parts. In MATLAB I would do something like:

vector=[0.2,1:60,60.8];

This results in a one dimensional array of 62 positions. I'm trying to implement this using scipy. The closest I am right now is this:

a=[[0.2],linspace(1,60,60),[60.8]]

However this creates a list, not an array, and hence I cannot reshape it to a vector array. But then, when I do this, I get an error

a=array([[0.2],linspace(1,60,60),[60.8]])
ValueError: setting an array element with a sequence.

I believe my main obstacle is that I can't figure out how to translate this simple operation in MATLAB:

a=[1:2:20];

to numpy. I know how to do it to access positions in an array, although not when creating a sequence. Any help will be appreciated, thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well NumPy implements MATLAB's array-creation function, vector, using two functions instead of one--each implicitly specifies a particular axis along which concatenation ought to occur. These functions are:

  • r_ (row-wise concatenation) and

  • c_ (column-wise)


So for your example, the NumPy equivalent is:

>>> import numpy as NP

>>> v = NP.r_[.2, 1:10, 60.8]

>>> print(v)
     [  0.2   1.    2.    3.    4.    5.    6.    7.    8.    9.   60.8]

The column-wise counterpart is:

>>> NP.c_[.2, 1:10, 60.8]

slice notation works as expected [start:stop:step]:

>>> v = NP.r_[.2, 1:25:7, 60.8]

>>> v
  array([  0.2,   1. ,   8. ,  15. ,  22. ,  60.8])

Though if an imaginary number of used as the third argument, the slicing notation behaves like linspace:

>>> v = NP.r_[.2, 1:25:7j, 60.8]

>>> v
  array([  0.2,   1. ,   5. ,   9. ,  13. ,  17. ,  21. ,  25. ,  60.8])


Otherwise, it behaves like arange:

>>> v = NP.r_[.2, 1:25:7, 60.8]

>>> v
  array([  0.2,   1. ,   8. ,  15. ,  22. ,  60.8])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...