编辑:在我的第一个解决方案收到迷人的 cmets 后,我提出了另一个解决方案,它比第一个解决方案需要更多的代码编辑,但到目前为止仍比其他解决方案少(将原始解决方案移至结束):
让我们定义一个函数来获取值并将它们保存在一个持久变量中
function list = cc(value)
persistent allCases
if isempty(allCases) || (nargin == 0 && nargout == 0)
allCases = {};
end
if nargin == 1,
allCases = [allCases value];
list = value;
end
if nargin == 0 && nargout == 1,
list = allCases;
end
end
现在您只需在switch 之前添加cc; 即可重置持久变量并将case 语句中的所有值传递给函数,并在otherwise 部分调用函数以读取值:
a = 'a';
v = 'c';
cc;
switch a
case cc({'b' v 1.2})
%Multiple cases
case cc(2)
%number
case cc(ones(2))
%matrix
otherwise
disp('Allowed cases are:');
cellfun(@disp, cc);
end
打印出来:
Allowed cases are:
b
c
1.2000
2
1 1
1 1
有风险的解决方案:这个解决方案可能违反了很多编程实践,但仍然可以作为 hack。假设您没有嵌套了switch 语句,那么您可以在otherwise 语句中调用这样的函数:
function allCases = getCases
st = dbstack('-completenames');
line = st(2).line;
fLines = importdata(st(2).file, sprintf('\n'));
switchLine = find(~cellfun(@isempty, ...
regexp(fLines(1:line-1), '^\s*switch\s', 'once')), 1, 'last');
otherwLine = find(~cellfun(@isempty, ...
regexp(fLines(1:line-1), '^\s*otherwise\s*$', 'once')), 1, 'last');
caseLines = fLines(switchLine+1:otherwLine-1);
casesStr = regexprep(caseLines(~cellfun(@isempty, ...
regexp(caseLines, '^\s*case\s', 'once'))), '^\s*case\s*', '');
casesCells = cell(size(casesStr));
for iCases = 1:numel(casesCells);
casesCells{iCases} = evalin('caller', casesStr{iCases});
end
allCases = [casesCells{:}];
end
如果你运行这样的代码
a = 'a';
v = 'c';
switch a
case {'b' v 1.2}
%Multiple cases
case 2
%number
case ones(2)
%matrix
otherwise
disp('Allowed cases are:');
cellfun(@disp, getCases);
end
打印出来
Allowed cases are:
b
c
1.2000
2
1 1
1 1