1

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.

2 Answers 2

2

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{:});
:
Sign up to request clarification or add additional context in comments.

Comments

2

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);

1 Comment

It's faster if you make an actual function, rather than an anonymous function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.