How do I let Matlab know which functions to call ?

1 vue (au cours des 30 derniers jours)
H ZETT M
H ZETT M le 12 Jan 2017
Modifié(e) : Adam le 23 Jan 2017
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 commentaires
Adam
Adam le 23 Jan 2017
Modifié(e) : Adam le 23 Jan 2017
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.
Stephen23
Stephen23 le 23 Jan 2017
Modifié(e) : Stephen23 le 23 Jan 2017
Adam gave most of the simplest answer:
funcs = {@Stokes, @Wind, @(x) Flow(x) };
toRun = [true, true, false];
cellfun(@(f)f(),funcs(toRun))

Connectez-vous pour commenter.

Réponse acceptée

Jordan Ross
Jordan Ross le 23 Jan 2017
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

Plus de réponses (0)

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by