switch with "ignore case" -> switchi
显示 更早的评论
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..
采纳的回答
更多回答(1 个)
Walter Roberson
2017-7-12
编辑:Walter Roberson
2017-7-12
1 个投票
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 个评论
Guillaume
2017-7-12
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
2017-7-12
Jan
2017-7-12
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.
类别
在 帮助中心 和 File Exchange 中查找有关 File Operations 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!