I have a set of code that, depending on how the program is initiated, will either be executed locally or sent to a remote machine for execution. The ideal way I imagine this could work would look something like the following:
line_of_code = 'do_something_or_other();';
if execute_remotely
send_via_udp(line_of_code);
else
eval(line_of_code);
end
The thing is, I know that the eval() function is ridiculously inefficient. On the other hand, if I write out line_of_code in each section of the if block, that opens the door for errors. Is there any other way that I can do this more efficiently than by simply using eval()?
EDIT: After more consideration and some discussion in the comments, I have my doubts that function handles can be transmitted via UDP. I’m therefore updating my answer, instead suggesting the use of the function FUNC2STR to convert the function handle to a string for transmission, then using the function STR2FUNC to convert it back to a function handle again after transmission…
To get around using EVAL, you can use a function handle instead of storing the line of code to be executed in a string:
The above assumes that the function
do_something_or_otheralready exists. You can then do something like the following on the remote system:As long as the code (i.e. m-file) for the function
do_something_or_otherexists on both the local and remote systems, I think this should work. Note that you could also use FEVAL to evaluate the function name string instead of converting it to a function handle first.If you need to create a function on the fly, you can initialize
fcnToEvaluateas an anonymous function in your code:And the code to send, receive, and evaluate this should be the same as above.
If you have arguments to pass to your function as well, you can place the function handle and input arguments into a cell array. For example:
In this case, the code for
send_via_udpmay have to break the cell array up and send each cell separately. When received, the function name string will again have to be converted back to a function handle using STR2FUNC.