我试图阅读这篇文章,但我认为我可能会从根本上走错路。这就是我想要的:
a='test1'
可能相差很大所以理想情况下,我认为我想要这样的案例结构:
a='test1';
switch a
case ~isempty(regexpi(a,'test','match','once')) %should handle all cases where 'test' is contained in the input string
disp('this');
otherwise %should handle everything else
disp('that');
end
但它总是输出that
。
如何解决这个问题?
答案 0 :(得分:2)
您正在使用 char
(字符数组)a
作为切换变量和 logical
(是/否) )表达式结果,否则将始终使用否则,因为 char
不是 logical
。
您可以将逻辑表达式结果用作切换变量,并以true
为例:
a='test1';
switch ~isempty(regexpi(a,'test','match','once'))
case true %should handle all cases where 'test' is contained in the input string
disp('this');
otherwise %should handle everything else
disp('that');
end
或仅使用if-else语句:
a='test1';
if ~isempty(regexpi(a,'test','match','once'))
disp('this');
else %should handle everything else
disp('that');
end
答案 1 :(得分:1)
如所写,您正在将布尔表达式的结果与要测试的值a
进行比较。这永远不会匹配,因此只需使用switch true
即可。
按顺序评估案件,因此等效于使用
if ...
% Do something
elseif ...
% Do something else
else
% Otherwise
end
有人可能会争辩的结构是可取的。