필터 지우기
필터 지우기

Storing function handles and executing them from a cell matrix

조회 수: 16 (최근 30일)
Daniel Cohen
Daniel Cohen 2023년 5월 4일
답변: Varun 2023년 5월 16일
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
Rik
Rik 2023년 5월 4일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Varun
Varun 2023년 5월 16일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by