MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   评估代码或通过udp传输的例程 (https://www.labfans.com/bbs/showthread.php?t=23480)

poster 2019-12-10 20:41

评估代码或通过udp传输的例程
 
我有一组代码,取决于程序的启动方式,这些代码将在本地执行或发送到远程计算机上执行。我认为这可行的理想方式如下所示:

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()之外,还有其他方法可以更有效地做到这一点吗?



[B]回答:[/B]

[B]编辑:[/B]经过更多考虑和评论中的一些讨论,我怀疑功能句柄可以通过UDP传输。因此,我正在更新我的答案,而不是建议使用函数[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/func2str.html"]FUNC2STR[/URL]将函数句柄转换为字符串以进行传输,然后在传输后使用函数[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/str2func.html"]STR2FUNC[/URL]将其重新转换回函数句柄...

要使用[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/eval.html"]EVAL解决问题[/URL] ,可以使用[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/f2-38133.html"]函数句柄,[/URL]而不是将要执行的代码行存储在字符串中:

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文件)在本地和远程系统上都存在,我认为这应该可以工作。请注意,您也可以使用[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/feval.html"]FEVAL[/URL]评估函数名称字符串,而不是先将其转换为函数句柄。

如果您需要即时创建函数,则可以在代码fcnToEvaluate初始化为[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/f4-70115.html"]匿名函数[/URL] :

fcnToEvaluate = @() disp('Hello World!'); %# Create an anonymous function 发送,接收和评估的代码应与上述相同。

如果您还具有要传递给函数的参数,则可以将函数句柄和输入参数放入[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/br04bw6-98.html"]单元格array中[/URL] 。例如:

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的代码[I]可能[/I]必须分解单元阵列并分别发送每个单元。收到函数名称字符串后,将再次不得不使用[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/str2func.html"]STR2FUNC[/URL]将其转换回函数句柄。



[url=https://stackoverflow.com/questions/2923914]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 01:07

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.