switch with "ignore case" -> switchi
Mostra commenti meno recenti
Just a question or a proposal for an enhancement:
Has anyone ever wondered, why there isn't an enhanced switch-function for ignoring the case of strings, like strcmp/strcmpi, regexp/regexpi. It would be just consistent to have a switchi function.
Currently, you always have to program this problem using switch lower(xxx) and change all cases to lower letters..
Risposta accettata
Più risposte (1)
Walter Roberson
il 12 Lug 2017
Modificato: Walter Roberson
il 12 Lug 2017
1 voto
The case labels are technically expressions rather than constants, so you can also wrap them in lower() calls instead of changing their content.
On the other hand, if you go into Preferences to Keyboard => Shortcuts, you can add a shortcut for "Change to Lower Case", which you would probably use by highlighting the text and giving the shortcut sequence. That might be easier than typing lower() around each of the labels.
I find that in practice I do not tend to use switch() very often, and certainly not with enough cases to make changing the labels to lowercase to be an issue. Instead I find that in the circumstances where someone might typically use a switch(), that I instead use data structures that contain both the text and the control information about what to do, and then it is a matter of applying a small analysis function to figure out the offset into the table and pulling out the control information and executing it.
3 Commenti
Guillaume
il 12 Lug 2017
I agree with Walter: once you're proficient in matlab/writing code you don't tend to use switch. Look up tables are usually more efficient than switch.
Thomas Becker
il 12 Lug 2017
Jan
il 12 Lug 2017
A switch with a bunch of cases is nicer than a stack of elseif branches:
switch lower(Command)
case 'start'
case 'stop'
case 'forget'
case 'relax'
otherwise % No SWITCH without OTHERWISE!
error('Programming error: Unexpected Switch expression!');
end
if strcmpi(Command, 'start')
elseif strcmpi(Command, 'stop')
elseif strcmpi(Command, 'forget')
elseif strcmpi(Command, 'relax')
else % No ELSEIF stack without ELSE!
error('Programming error: Unexpected ELSEIF branch!');
end
With switch you have a list with arguments, with elseif a list of commands for the comparisons. Therefore I think that switch is leaner.
Using a data structure instead is useful, if the list of commands is expanded dynamically and if a look-up-table is applicable at all.
Categorie
Scopri di più su File Operations in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!