Storing function handles and executing them from a cell matrix

11 views (last 30 days)
Hello,
I am wrtining a progarm which contian alot of user defined functions (around 300 unique ones). From input of boolean vector, the prograpm needs to call only for specific functions as seen below:
FunctionsToCall = {ExecuteSet1, function_1_1(input11), function_1_2(input12)...;
ExecuteSet2, function_2_1(input21), function_2_2(input22)...;
...}
for idx = 1:N
if FunctionsToCall{idx}{1}
for jdx = 1:N
input = InputMatix{idx}{jdx}
functionincell = FunctionsToCall{idx}{jdx};
output = functionincell(input);
end
end
end
function output = function_1_1(input)
%things to execute
end
function output = function_1_2(input)
%things to execute
end
.
.
.
How can I do that? my only other idea that comes to mind is to use alot of "if" statements.
take note that each function have a different input.
  1 Comment
Rik
Rik on 4 May 2023
I have some trouble understanding your setup. Try to make a MWE so we can run your code without any other dependencies and can reproduce your current setup.
Currently it looks like the functions are already executed when you create FunctionsToCall, which doesn't seem to match your intent.

Sign in to comment.

Accepted Answer

Varun
Varun on 16 May 2023
From the code snippet attached, I believe that you want to store function handles in a cell array named FunctionsToCalland then, execute these functions selectively by passing the input arguments from another variable called InputMatrix. This can be implemented as follows:
  1. In the variable “FunctionsToCall, the function handles can be stored correctly as follows-
FunctionsToCall = {ExecuteSet1, @function_1_1, @function_1_2,;
ExecuteSet2, @function_2_1, @function_2_2;
}
I assume that terms like “input11”, “input12” are placeholders for the actual input arguments and not the arguments themselves. Because in the “for” loop of the code snippet, the functionincell” is called on the variable “input.
2. You can use the “feval” function to execute the function handle inside the for loop. So, the overall code will look as follows:
FunctionsToCall = {ExecuteSet1, @function_1_1, @function_1_2,;
ExecuteSet2, @function_2_1, @function_2_2,;
}
for idx = 1:N
if FunctionsToCall{idx,1}
for jdx = 1:N
input = InputMatrix(idx,jdx);
functionincell = FunctionsToCall(idx,jdx);
output = feval(functionincell{:},input);
end
end
end
function output = function_1_1(input)
%things to execute
end
function output = function_1_2(input)
%things to execute
end
To learn more about “feval”, you may refer to the following documentation: https://www.mathworks.com/help/matlab/ref/feval.html

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!