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!