switch case efficiency question

조회 수: 11 (최근 30일)
Chong Tao
Chong Tao 2013년 9월 14일
I have a question about switch/case structure.
if true
switch input[a,b]
case [1,1]
do something 1
case [1,2]
do something 2
case ...
... etc.
end
since a =1 to 40 and b = 1 to 11. So i will end up with a few hundred cases. How to make the code doing the selection more efficient? Thanks, Chong

채택된 답변

Image Analyst
Image Analyst 2013년 9월 14일
First of all, a few hundred tests is nothing - it will take just a very small fraction of a second to test 440 cases. Now if you had millions of tests, that might take some time. However looking at a switch statement that spans several thousand lines is difficult. So how you can compact that depends on what "something" is. If it's something that depends on a and b then you could just make the whole thing a single function. But if it really does unique operations in each case block, then you may be stuck. Is there anyway the "somethings" could be made into a single function taking a and b as an input? And I don't mean just transferring 440 tests inside the function. I mean like the something can be parameterized, like out=10*a+42*b or something like that.
  댓글 수: 1
Image Analyst
Image Analyst 2013년 9월 14일
Responding to Chong's "Answer"... No, adding a break won't make it faster since it automatically breaks anyway once it does the case block.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Chong Tao
Chong Tao 2013년 9월 14일
Thank you very much, Image Analyst.
"doing something " in each case is unique. it is not a function of a, b. Do you think add a break command to each case will make it faster since there will be only one match anyway?
switch input[a,b]
case [1,1]
M =18; break
case [1,2]
M =20
case ...
... etc.
end

Jan
Jan 2013년 9월 15일
Please post the problem in valid Matlab syntax. "switch input[a,b]" could mean a variety of different things.
Your code example seems to be a look-up-table. Then this would be more efficient:
a = 1;
b = 2;
lut = [18, 20, 23; 19, 26, 65];
M = lut(a, b);
  댓글 수: 2
Chong Tao
Chong Tao 2013년 9월 15일
Thanks Jan. A look-up-table will definitely do the job. I never thought about this. :)
Image Analyst
Image Analyst 2013년 9월 15일
I thought "Do something" meant executing a bunch of code that was all unique, not just assigning a single variable like M. If it's really as simple as assigning some variable, then a look up table would work. If they're integers you can use intlut() in the Image Processing Toolbox.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by