How do I let Matlab know which functions to call ?
1 次查看(过去 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 中查找有关 Whos 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!