P i
P i

Reputation: 30674

Passing multiple parameters between functions

I am looking at the following design pattern:

x_min = minimize( 'f', x_initial, step_size, p1, p2, p3, p4, p5 );

... where f is some function ...

function y = f( x, p1, p2, p3 )
    :
end

... for which minimize will attempt to find a local minimum:

function x_min = minimize( FUNC_NAME, x_initial, step_size, p1, p2, p3, p4, p5 )
    X = x_initial;

    % compose string used to call function
    argstr = [FUNC_NAME, '(X']; 
    for i = 1:(nargin - 3)
        argstr = [argstr, ',p', int2str(i)];
    end
    argstr = [argstr, ')'];
    :
    x1 = eval( argstr ); % etc
    :

It is very ugly -- for a start it ties eval( argstr ) to only executing f on X.

It's rather old code (dated 2001).

Is there a preferred way to handle this scenario nowadays?

Is there any way to accomplish this so that the implementation of f is at the call-site? i.e. invisible to minimize.m? The existing pattern requires it is in separate f.m file.

Upvotes: 1

Views: 58

Answers (2)

Erfan
Erfan

Reputation: 1927

Generally, it is not recommended to use eval.

If the number of input arguments is unknown and variable, you can include varargin as an input argument and pass the function handle instead of the function name. varargin brings a flexible number of input arguments together as a cell array and passes them to the function:

function out = anyfun(func_handle, varargin)
out = func_handle(varargin{:})

As an example:

anyfun(@mod, 123, 100)

ans =

    23

For your example, you should define the function like:

function x_min = minimize(FUNC_handle, x_initial, step_size, varargin)
:
x1 = FUNC_handle(varargin{:});
:

Upvotes: 2

Rotem
Rotem

Reputation: 32084

For executing f on X, you can use Function Handles.
Example: f = @sin; f(pi/2) results ans = 1.

For implementation of f at the call-site, you can use an Anonymous Function

Example:
Executing minimize for function f(x) = x^2:

x_initial = 1;
step_size = 0.01;
q = minimize(@(x) x.^2, x_initial, step_size);

minimize implementation example (simplified implementation of minimum finding):

function x_min = minimize(f, x_initial, step_size)
    X = x_initial-10:step_size:x_initial+10; %Prepare input array for f.
    Y = f(X);
    x_min = min(Y);

Upvotes: 2

Related Questions