MATLAB Answers

How do I let Matlab know which functions to call ?

1 view (last 30 days)
H ZETT M
H ZETT M on 12 Jan 2017
Edited: Adam on 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 Comments
Stephen Cobeldick
Stephen Cobeldick on 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))

Sign in to comment.

Accepted Answer

Jordan Ross
Jordan Ross on 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

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!