Tuesday, March 13, 2012

Subfunctions in Octave/Matlab

Consider the contents of the following Matlab program "mainFunction.m".

%
% A function that integrates the function
% given by the routine subFunction(x)
% over the range a and b
%

function I = mainFunction(a,b)
   a = -5;
   b = 5;
   I = quad('subFunction', a, b)
%  keyboard  % uncomment if needed
endfunction
 
%
% some nontrivial function
%

function y=subFunction(x)
   if( x > 0)
      y = x^2;
   else
      y = x;
   endif
endfunction

The function to be integrated, subFunction(x), can be saved as a separate file called subFunction.m, or, as in this case, it can be included in the same file as the main function. There are advantages to both these techniques.

If I store functions in their own individual files, I can call them from any other function. However, I can very easily end up with a lot of files. This may not necessarily be a bad thing, but it can be a challenge beyond a point.

If I use the subfunctions (as above), then the subfunctions themselves remain invisible outside the file in which they are contained. They may be accessed by the main function and other subfunctions within the same file.

Unfortunately, you cannot use "subfunctions" with script files. A useful workaround is to wrap a function declaration around your script, and use the command keyboard (as shown in the commented line in the example above) to transfer control out.

From here you can examine all the variables local to the "script".

When you are done, say dbquit, or return.

No comments: