Dynamically get list of switch cases in code

16 views (last 30 days)
Hi all, I have a class measurement device with a property named unit. Each different unit requires a different command to be sent over GPIB, so I have a switch statement for that. Is there some way to get a list/(cell)array of all these switch cases from the object or the function inside the object? This would be very convenient because then I have to define new "cases" in only one place and have for example a GUI update automatically.
Is something like this possible, or do I have to take a different approach?

Accepted Answer

Stephen23
Stephen23 on 29 Aug 2018
Edited: Stephen23 on 29 Aug 2018
"Is something like this possible..."
Possible, yes. Easy, no.
Getting the switch conditions dynamically requires parsing the code itself, which is inefficient and fragile:
"or do I have to take a different approach?"
If you put the data into a structure then you can get much the same effect as a switch, with the advantage that you can easily get a list of the "conditions". Instead of a switch like this:
switch str
case 'A'
val = 1;
case 'B'
val = 2;
...
end
you can use the fields of a structure:
S.A = 1;
S.B = 2;
...
val = S.(str);
and get the possible "conditions" simply using fieldnames:
opts = fieldnames(S)
This will be much more efficient than any method to get the switch conditions automatically.
  2 Comments
fvanzwol
fvanzwol on 29 Aug 2018
Thank you for answering so quickly! I think using structures is the way to go then. Each switch statement actually has a few lines of code. Can I just insert these lines into the structure and then evaluate the code using eval() ?
Stephen23
Stephen23 on 29 Aug 2018
Edited: Stephen23 on 29 Aug 2018
" Can I just insert these lines into the structure and then evaluate the code using eval() ?"
I would not recommend doing that:
I had a similar problem recently, which I solved by using nested functions and placing their function handles into a structure: this made it easy to write arbitrary code inside the nested function and use the structure to call them:
S.A = @foo;
S.B = @baz;
...
fieldnames(S) % get "conditions"
...
S.(str)(...) % call any one function
...
function foo(...)
...
end
function baz(...)
...
end
Much more efficient than parsing files, or using ugly eval. Much easier to maintain and debug.

Sign in to comment.

More Answers (0)

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!