How can I create function pointers from a string input in MATLAB?

跟風遠走 提交于 2019-11-30 13:10:25

Option #1:

Use the str2func function (assumes the string in type is the same as the name of the function):

p = str2func(type);  % Create function handle using function name
c = p(phi, lambda);  % Invoke function handle

NOTE: The documentation mentions these limitations:

Function handles created using str2func do not have access to variables outside of their local workspace or to nested functions. If your function handle contains these variables or functions, MATLAB® throws an error when you invoke the handle.

Option #2:

Use a SWITCH statement and function handles:

switch type
  case 'Mercator'
    p = @Mercator;
  case 'KavrayskiyVII'
    p = @KavrayskiyVII;
  ...                    % Add other cases as needed
end
c = p(phi, lambda);      % Invoke function handle

Option #3:

Use EVAL and function handles (suggested by Andrew Janke):

p = eval(['@' type]);  % Concatenate string name with '@' and evaluate
c = p(phi, lambda);    % Invoke function handle

As Andrew points out, this avoids the limitations of str2func and the extra maintenance associated with a switch statement.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!