Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
|
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
我有一组代码,取决于程序的启动方式,这些代码将在本地执行或发送到远程计算机上执行。我认为这可行的理想方式如下所示:
line_of_code = 'do_something_or_other();'; if execute_remotely send_via_udp(line_of_code); else eval(line_of_code); end 问题是,我知道eval()函数效率低得离谱。另一方面,如果我在if块的每个部分中写出line_of_code , if打开出现错误的大门。除了简单地使用eval()之外,还有其他方法可以更有效地做到这一点吗? 回答: 编辑:经过更多考虑和评论中的一些讨论,我怀疑功能句柄可以通过UDP传输。因此,我正在更新我的答案,而不是建议使用函数FUNC2STR将函数句柄转换为字符串以进行传输,然后在传输后使用函数STR2FUNC将其重新转换回函数句柄... 要使用EVAL解决问题 ,可以使用函数句柄,而不是将要执行的代码行存储在字符串中: fcnToEvaluate = @do_something_or_other; %# Get a handle to the function if execute_remotely fcnString = func2str(fcnToEvaluate); %# Construct a function name string %# from the function handle send_via_udp(fcnString); %# Pass the function name string else fcnToEvaluate(); %# Evaluate the function end 上面假设函数do_something_or_other已经存在。然后,您可以在远程系统上执行以下操作: fcnString = receive_via_udp(); %# Get the function name string fcnToEvaluate = str2func(fcnString); %# Construct a function handle from %# the function name string fcnToEvaluate(); %# Evaluate the function 只要功能do_something_or_other的代码(即m文件)在本地和远程系统上都存在,我认为这应该可以工作。请注意,您也可以使用FEVAL评估函数名称字符串,而不是先将其转换为函数句柄。 如果您需要即时创建函数,则可以在代码fcnToEvaluate初始化为匿名函数 : fcnToEvaluate = @() disp('Hello World!'); %# Create an anonymous function 发送,接收和评估的代码应与上述相同。 如果您还具有要传递给函数的参数,则可以将函数句柄和输入参数放入单元格array中 。例如: fcnToEvaluate = @(x,y) x+y; %# An anonymous function to add 2 values inArg1 = 2; %# First input argument inArg2 = 5; %# Second input argument cellArray = {fcnToEvaluate inArg1 inArg2}; %# Create a cell array if execute_remotely cellArray{1} = func2str(cellArray{1}); %# Construct a function name string %# from the function handle send_via_udp(cellArray); %# Pass the cell array else cellArray{1}(cellArray{2:end}); %# Evaluate the function with the inputs end 在这种情况下, send_via_udp的代码可能必须分解单元阵列并分别发送每个单元。收到函数名称字符串后,将再次不得不使用STR2FUNC将其转换回函数句柄。 更多&回答... |
![]() |
![]() |