switch within if statement vs if/elseif efficiency
이전 댓글 표시
Hi!
I'm doing an assignment where I have to code Conway's Game of Life.
Currently I'm attempting to create a GUI for ease of entering initial conditions.
prev=false(m,n)
[rows,cols]=size(prev);
clf
plotroutine(prev)
title({'Instructions'})
gate=true;
while gate==true
[x,y,key]=ginput(1);
if key~=[] %This is line 9!
switch key
case 1
if 0<x&&x<cols&&0<y&&y<rows
col=ceil(x);
row=rows-floor(y);
prev(row,col)=~prev(row,col);
clf
plotroutine(prev)
title({'Instructions'})
end
case 114
prev=logical(randi([0,1],rows,cols));
clf
plotroutine(prev)
title({'Instructions'})
case 32
gate=false;
title([])
end
end
While I was testing edge case scenarios, more specifically the [Enter] and [Windows] key, ginput returned []. However, this is not a valid argument for switch. Thus I had to write line 9 instead.
My question is whether this implementation, or merging the if and switch statements to a single if/elseif statment is more efficient/preferrable from a best practice point of view?
댓글 수: 4
Stephen23
2017년 11월 10일
The comparison key~=[] does not do what you seem to think it does: it will return an empty output whenever key is scalar or the same size as []. There does not seem to be any point to that. Much better would be to test if key is empty using standard MATLAB commands:
if ~isempty(key)
Shuai Shao
2017년 11월 10일
편집: Shuai Shao
2017년 11월 10일
Shuai Shao
2017년 11월 10일
채택된 답변
추가 답변 (1개)
Steven Lord
2017년 11월 10일
1 개 추천
Your code doesn't handle the case where the user does something to finish the ginput call other than click the left mouse button, press the 'r' key, or press the space key. Therefore the while loop simply continues. If you want a "catch all" that lets you handle those other cases differently than simply continuing on, use the otherwise keyword.
Inside the otherwise block you could:
- check if key isempty as Stephen suggested
- display some text telling the user what they need to do
- issue a warning
- throw an error
- let the while loop simply continue while the otherwise block makes it explicitly clear that that's how you want those other cases to be handled
- or some combination of any or all of the above.
댓글 수: 2
Shuai Shao
2017년 11월 10일
편집: Shuai Shao
2017년 11월 10일
Steven Lord
2017년 11월 10일
Ah yes, I had forgotten about switch requiring the expression to be a scalar or a char vector.
You could combine the two.
if isempty(key)
% handle the empty case
else
switch key
% add case and/or otherwise blocks here
end
end
or
if ~isempty(key)
switch key
case 1
% etc
end
end
카테고리
도움말 센터 및 File Exchange에서 Board games에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!