Dynamically get list of switch cases in code

4 ビュー (過去 30 日間)
fvanzwol
fvanzwol 2018 年 8 月 29 日
編集済み: Stephen23 2018 年 8 月 29 日
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?

採用された回答

Stephen23
Stephen23 2018 年 8 月 29 日
編集済み: Stephen23 2018 年 8 月 29 日
"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 件のコメント
fvanzwol
fvanzwol 2018 年 8 月 29 日
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 2018 年 8 月 29 日
編集済み: Stephen23 2018 年 8 月 29 日
" 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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeVariables についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by