ritualmagick - 3 months ago 15

Python Question

Working on my Python these days, and I want to port a short Matlab code from a course I did a few years back into Python, but to be honest I can't figure out if it's possible to do it in the same manner, and if it is, how to do it.

The essential part here that I'm struggling with in Python is the following:

`nk = @(x)1`

for l=1:3 % calculate basis

nk = @(x)(nk(x).*(x-1));

end

How the code works in Matlab:

`nk = @(x)1`

`nk(x)`

`nk(xi)`

`xi=[1,2,3,4]`

`x`

In the for-loop,

`nk(x)`

`(x-1)`

`x`

`nk = (x-1)*(x-1)*(x-1)`

It is still a function which I can call as

`nk(x)`

`x`

Answer

The following crude example of piecewise linear interpolation might give you an idea:

```
def interpolate(xs,ys):
#assumes that xs and ys are same-length lists
#of real numbers, with xs sorted
def N(x):
if x < min(xs) or x > max(xs): return False #we don't extrapolate
if x == max(xs): return ys[-1]
i = 0
while xs[i] <= x:
i+= 1
m = (ys[i]-ys[i-1])/(xs[i]-xs[i-1])
return ys[i-1] + m*(x - xs[i-1])
return N
```

For example,

```
>>> f = interpolate([0,1,2],[1,2,4])
>>> f(0)
1.0
>>> f(0.7)
1.7
>>> f(1.9)
3.8
>>> f(2)
4
>>> f(2.1)
False
```

The key concept is that of *closures*. See this blog post for a nice discussion (especially the part that talks about function factories).

By the way, you can create closures with anonymous functions, though the resulting code isn't very readable:

```
>>> f = (lambda x: (lambda y: x+y))
>>> g = f(3)
>>> g(2)
5
```

Since you were mentioning function "handles", I don't think that you really want anonymous functions (especially given your original question that had more Matlab code).