Create linear spaced vector?

Adam DePrince adam at cognitcorp.com
Fri Dec 17 14:12:03 EST 2004


On Fri, 2004-12-17 at 13:39, kjm wrote:
> Hi Everyone,
> 
> I am trying to port some old MatLab code to python, and am stuck on
> how to accomplish something.
> 
> I am trying to write a generalized function that will create a
> linearly spaced vector, given the start and end point, and the number
> of entries wanted.
> 
> In MatLab I have this function that I wrote:
> 
> [code]
> 
> function out = linearspace(x1,x2,n)
> 
> out = [x1+ (0:n-2)*(x2 - x1)/(floor(n)-1) x2];
> 
> return
> 
> 
> [/code]
> 
> 
> I have the numeric package, numarray installed, and I think it should
> be accomplished easily, but I just can't seem to get the syntax
> correct with python.
> 
> Any tips would be greatly appreciated.
> 
> 
> Thanks

Is this want you want?

#!/usr/bin/python

def linear_space( start, end, count ):

    """ Returns a vector containing count evently spaced intervals
(count + 1 evenly spaced points) """
    
    delta = (end-start) / float(count)
    return [start,] + \
map( lambda x:delta*x + start, range( 1, count  ) ) + [end, ] 

if __name__ == "__main__":
    print linear_space( 1.0, 2.0, 10 )

Running it gives you: 
 [1.0, 1.1000000000000001, 1.2, 1.3, 1.3999999999999999, 1.5,
1.6000000000000001, 1.7000000000000002, 1.8, 1.8999999999999999, 2.0]



Adam DePrince 





More information about the Python-list mailing list