MATLAB: Dynamically get list of switch cases in code

classdynamicallygetlistMATLABswitch

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?

Best Answer

"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.