How do I let Matlab know which functions to call ?

2 visualizzazioni (ultimi 30 giorni)
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 Commenti
Adam
Adam il 23 Gen 2017
Modificato: Adam il 23 Gen 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 il 23 Gen 2017
Modificato: Stephen23 il 23 Gen 2017
Adam gave most of the simplest answer:
funcs = {@Stokes, @Wind, @(x) Flow(x) };
toRun = [true, true, false];
cellfun(@(f)f(),funcs(toRun))

Accedi per commentare.

Risposta accettata

Jordan Ross
Jordan Ross il 23 Gen 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

Più risposte (0)

Categorie

Scopri di più su Data Type Identification in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by