switch within if statement vs if/elseif efficiency
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Shuai Shao
el 10 de Nov. de 2017
Comentada: Steven Lord
el 10 de Nov. de 2017
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 comentarios
Respuesta aceptada
Stephen23
el 10 de Nov. de 2017
Use whichever one is clearest for understanding the program. You will spend more time reading and fixing the code than one if statement will spend running.
0 comentarios
Más respuestas (1)
Steven Lord
el 10 de Nov. de 2017
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 comentarios
Steven Lord
el 10 de Nov. de 2017
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
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!