Adnan j
Adnan j

Reputation: 119

Dynamic function handles Matlab

I have the following function handle

rhs = @(t,p,m) function_name (t,p,m,variables)

and I need to dynamically name the function_name in the call above so I can later call the handle in other part of the code

For example:

odesolver(rhs);

I've tried for example :

function_names_array = ['function_1','function_2','function_3'];
paramters_array = [parameters_array_1,parameters_array_2,parameters_array_3]
for i=1:3
for j= 1:5

rhs = @(t,p,m) function_names_array(i)(t,p,m,parameters(j))

end 
end 

This will not work.

Upvotes: 1

Views: 451

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60444

Probably what you want to do is create multiple function handles, then select one of them dynamically. For example:

functions = {@function_1, @function_2, @function_3};
parameters = {
   {1,[10,20],'a'}
   {2,[10,20],'c'}
   {3,[100,200],'a'}};
for i=1:numel(functions)
  for j=1:numel(parameters)
    rhs{i,j} = @(t,p,m) functions{i}(t,p,m,parameters{j}{:})
  end 
end 

odesolver(rhs{2,4});

It is not possible to create an array of function handles (the syntax would be ambiguous), but it is possible to collect them in a cell array as above.

The parameters are also collected in a cell array, this allows for a lot of flexibility. Each set of parameters is again a cell array. parameters{j}{:} is a comma-separates list of the elements in cell array j, ideal for using as the argument list in a function call.


Regarding nomenclature: @function_1 is a handle to a named function. @()... is an anonymous function (called lambda in other languages). An anonymous function is one that has no name, but can be assigned to a function handle and be used that way. Either way, the function handle is a way of using a function as a variable: you can pass them as arguments to functions, return them from functions, and store them in cell arrays or struct arrays. A string with the name of a function does not have the same function: you cannot call a function through a string with its name (unless you use feval or eval).

Upvotes: 2

Related Questions