p***@gmx.de
2011-11-30 21:17:31 UTC
Hi,
I'm new to Octave (but not to Matlab). I've encountered a problem that
is bound to have an extremely simple solution:
Want to call a function in a function file. This first function
references a second function in the same function file. So far so
good. However, I want to make some variables global so that they can
be accessed in the second function WITHOUT passing them as an
argument, e.g.
function FirstFunction()
global x = 3;
..
y = SecondFunction(a)
endfunction
function r = SecondFunction(a)
a*x %display 3*a
endfunction
(I cannot pass x as an argument because in reality, SecondFunction is
used by the nonlinear optimizer (nonlin_curvefit), which in turn
requires SecondFunction to accept only the variable parameters.)
However, in the above code, x is not recognized in SecondFunction. Why
not?
I have tried several options:
1. Making a script file (i.e. a file not starting with function),
setting global x = 3 there, calling the functions required which are
defined later on in the file. Octave does not recognize the functions.
2. Nested functions do not work.
3. Define anonymous functions in the main function file (i.e. replace
SecondFunction with @(parameters) ... This works fine, however I
cannot guarantee that in future all my functions will be on one line.
Therefore, the generation of anonymous functions is really only an
emergency solution.
How can global variables be passed on to functions?
Best regards,
Philip
I'm new to Octave (but not to Matlab). I've encountered a problem that
is bound to have an extremely simple solution:
Want to call a function in a function file. This first function
references a second function in the same function file. So far so
good. However, I want to make some variables global so that they can
be accessed in the second function WITHOUT passing them as an
argument, e.g.
function FirstFunction()
global x = 3;
..
y = SecondFunction(a)
endfunction
function r = SecondFunction(a)
a*x %display 3*a
endfunction
(I cannot pass x as an argument because in reality, SecondFunction is
used by the nonlinear optimizer (nonlin_curvefit), which in turn
requires SecondFunction to accept only the variable parameters.)
However, in the above code, x is not recognized in SecondFunction. Why
not?
I have tried several options:
1. Making a script file (i.e. a file not starting with function),
setting global x = 3 there, calling the functions required which are
defined later on in the file. Octave does not recognize the functions.
2. Nested functions do not work.
3. Define anonymous functions in the main function file (i.e. replace
SecondFunction with @(parameters) ... This works fine, however I
cannot guarantee that in future all my functions will be on one line.
Therefore, the generation of anonymous functions is really only an
emergency solution.
How can global variables be passed on to functions?
Best regards,
Philip