Search code examples
functionoctaveanonymous

Octave : use anonymous function inside function


Is there a way in Octave to use anonymous functions inside of a function? I want to avoid having a dependency between the function file and the config file. The link to the config file should only be from inside main.m.


My project has the following file structure:

% config.m
ms2kmh = @(v) v * 3.6;
% main.m
source('config.m');
source('application.m');
% application_xy.m
x = 1;
y = 2;
A = function_xy(x, y)
% function_xy.m
function A = function_xy(x, y)
    source('config.m'); % <-- want to avoid this line
    A = x * ms2kmh(y);
end

thank you


Solution

  • Sounds like you are trying to create an object with state (in this case, the x, y inputs, and the desired function handle). E.g.

    % @application_xy/application_xy.m
    function Obj = application_xy(x, y, fhandle)
      Obj = struct( 'x', x, 'y', y, 'f', fhandle );
      Obj = class( Obj, 'application_xy' );
    end
    

    % @application_xy/function_xy.m
    function A = function_xy(Obj)
        A = Obj.x * Obj.f( Obj.y );
    end
    

    % config.m
    ms2kmh = @(v) v * 3.6; 
    

    % main.m
    source('config.m');
    MyObj = application_xy(1, 2, ms2kmh );
    A = function_xy( MyObj )
    

    This is the manual entry on object oriented programming in octave if you're not too familiar with it and would like to read more.