help-octave
[Top][All Lists]

## Re: How to implement a summation function for numerical solving?

 From: John W. Eaton Subject: Re: How to implement a summation function for numerical solving? Date: Tue, 14 Jun 2011 09:16:21 -0400

```On 14-Jun-2011, andrewcd wrote:

| One more question:
|
| You have probably noticed that my code defines variables twice -- once
| inside and once outside of the function.  This is a pain, obviously.  But
| variables defined outside of the function don't show up inside the function,
| and vice versa.  There must be a way around this.  Any hints?  Thanks.

Pass more than one input as needed.  For example,

mu = 2
xmin = -5
xmax = 10
x = xmin:.2:xmax
lx = length(x)
stp = .2

function result = eqns (z, mu, xmin, xmax, x, lx, stp)
...
endfunction

Then you can set up the call to your function with

mu = 2
xmin = -5
xmax = 10
x = xmin:.2:xmax
lx = length(x)
stp = .2
z = something;

result = eqns (z, mu, xmin, xmax, x, lx, stp)

If you need to pass this function to fsolve, which expects a function
of a single variable, then you can use an anonymous function:

mu = 2
xmin = -5
xmax = 10
x = xmin:.2:xmax
lx = length(x)
stp = .2

result = fsolve (@(z) eqns (z, mu, xmin, xmax, lx, stp), guess)

All variables not listed in the argument list of the anonymous
function are picked up from the surrounding context.  So in

@(z) eqns (z, mu, xmin, xmax, lx, stp)

everything but Z is set from the variables that are in scope at the
point where the anonymous function is created.

Does that help?

jwe

```