如何从MATLAB中输入的字符串创建函数指针? [英] How can I create function pointers from a string input in MATLAB?
问题描述
如果我在MATLAB中使用inline
函数,则可以创建一个函数名称,该名称可能会根据之前的选择而有所不同:
If I use the inline
function in MATLAB I can create a single function name that could respond differently depending on previous choices:
if (someCondition)
p = inline('a - b','a','b');
else
p = inline('a + b','a','b');
end
c = p(1,2);
d = p(3,4);
但是我正在创建的内联函数变得非常具有史诗性,因此我想将它们更改为其他类型的函数(即m文件,子函数或嵌套函数).
But the inline functions I'm creating are becoming quite epic, so I'd like to change them to other types of functions (i.e. m-files, subfunctions, or nested functions).
假设我有m个文件,例如Mercator.m
,KavrayskiyVII.m
等(都带有phi
和lambda
的值),我想将所选函数分配给p
以与上面相同的方式进行调用,因此我可以多次调用它(使用可变大小的矩阵以及使用eval
可能导致的混乱或完全混乱的事情).
Let's say I have m-files like Mercator.m
, KavrayskiyVII.m
, etc. (all taking a value for phi
and lambda
), and I'd like to assign the chosen function to p
in the same way as I have above so that I can call it many times (with variable sized matrices and things that make using eval
either impossible or a total mess).
我有一个变量type
,它将是所需功能的名称之一(例如'Mercator'
,'KavrayskiyVII'
等).我想我需要使p
成为指向type
变量内部命名的函数的指针.有什么想法可以做到吗?
I have a variable, type
, that will be one of the names of the functions required (e.g. 'Mercator'
, 'KavrayskiyVII'
, etc.). I figure I need to make p
into a pointer to the function named inside the type
variable. Any ideas how I can do this?
推荐答案
选项#1:
使用 str2func
函数(假设字符串位于type
与函数的名称相同):
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:
使用
str2func
创建的函数句柄无权访问其本地工作空间之外的变量或嵌套函数.如果您的函数句柄包含这些变量或函数,则在调用句柄时MATLAB®会引发错误.
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.
选项2:
使用 SWITCH 语句和
使用 EVAL 和 Andrew Janke ): 正如安德鲁指出的那样,这避免了 As Andrew points out, this avoids the limitations of 这篇关于如何从MATLAB中输入的字符串创建函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!选项3:
p = eval(['@' type]); % Concatenate string name with '@' and evaluate
c = p(phi, lambda); % Invoke function handle
str2func
的限制以及与switch语句相关的额外维护.str2func
and the extra maintenance associated with a switch statement.