How do I let Matlab know which functions to call ?
조회 수: 2 (최근 30일)
이전 댓글 표시
So what I want to do is basically something like this:
Stokes = 'enabled'
Wind = 'enabled'
Flow = 'disabled'
I want matlab just to know "ok, I should compute Stokes and Wind via their functions, but not the flow". I could do this with a wild variation of if statements, but this would be probably ugly. Is there any way to get it working the way I want ? The problem is that I have to call the functions quite often (probably over 10k times), so I do not want matlab to check in every step if a particular function should get called or not.
댓글 수: 2
Adam
2017년 1월 23일
편집: Adam
2017년 1월 23일
As an addition to Jordan's answer below, it would be a little simpler if you just use logicals rather than strings if you only have two options i.e.
Stokes = true;
Wind = true;
Flow = false;
If you have a lot of cases then I would imagine working with logicals and logical indexing would be faster than string comparisons.
Better still, you could just put them all into an array, either just using two arrays that you keep track of yourself to ensure they are in sync. Also, if you can, use function handles rather than strings for their names if you can, e.g (the 'x' in the Flow is just to give an example of a function handle with arguments).
funcs = { @Stokes, @Wind, @(x) Flow(x) }
toRun = [true, true, false];
or you could use a map, e.g.:
map = containers.Map( { 'Stokes'; 'Wind'; 'Flow'} , { {@Stokes, true}, {@Wind, true}, {@(x) Flow(x), false } } );
Then index into this using your string names as normal and extract both the function handle and the logical, or you could just leave out the function handle there and do that part exactly as Jordan suggests.
채택된 답변
Jordan Ross
2017년 1월 23일
Hello,
One approach that you could consider is doing an initial setup step where you stored the names of the functions that you wanted into a cell array. Then, loop through the cell array and call "feval".
For example consider the following:
A = {'funcA', 'enabled'};
B = {'funcB', 'enabled'};
C = {'funcC', 'disabled'};
allFunctions = [A; B; C];
% Setup:
funcToRun = allFunctions(strcmp(allFunctions(:,2),'enabled'));
% Run all the enabled functions
for i=1:size(funcToRun,1)
feval(funcToRun{i,1});
end
function funcA
disp('A');
end
function funcB
disp('B');
end
function funcC
disp('C');
end
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Identification에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!