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 CenterFile Exchange에서 Variables에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by