简体   繁体   中英

How to define a function with a parameter in it in Octave?

I am trying to define a function with a predefined variable, and Octave says that the variable was not defined. I am trying to run the following code in Octave,

q = 5;
function w = tointegrate(x)
  w = 2 * q * sin(x);
endfunction
[ans, ier, nfun, err] = quad("tointegrate", -10*q, 10*q);
ans

Octave gives the error

error: 'q' undefined near line 3 column 10 error: quad: evaluation of user-supplied function failed

How to fix this error?

You are expecting 'commandline functions' in octave to have lexical scope, but this is simply not the case.

If all of this was inside a function, and you defined a nested function, it would work as you expect. But 'commandline functions' like this are treated as if they are in their own file, and have no knowledge of the workspace in which they've been defined.

In this particular case, since your function is effectively a one-liner, you can get the effect you want by making it a function handle instead, which 'does' capture the local workspace. Ie this will work

q = 5;
tointegrate = @(x) 2 * q * sin(x);
[ans, ier, nfun, err] = quad("tointegrate",-10 *q ,10*q);

Note, however, that 'q' will have the value it had at the time it was captured. Ie if you update q dynamically, its value will not be updated in the function handle.

Otherwise, for more complex functions, the solution is really to pass it as a parameter (or to access it as a global etc).

You can solve this by having q be a parameter to the function, then creating an anonymous function to call quad , like so:

function w = tointegrate(x, q)
  w = 2 * q * sin(x);
endfunction

q = 5;
[ans, ier, nfun, err] = quad(@(x)tointegrate(x,q), -10*q, 10*q);
ans

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM