在octave (也许还有matlab)中,似乎没有办法打破switch语句,但我不确定.
P=rand(2,20);
mu=mean(P,2);
dim=2;
plot_mean=false;
for i=1:1
switch (dim)
case 2
% Print points as dots
plot(P(1,:),P(2,:),'.');
if (!plot_mean)
break;
endif
hold on
% Print mean values as red circles
plot(mu(1,:),mu(2,:),'or');
% Quite some more code following here with again several if statements that need to be broken out
case 3
% Similar for 3D case
% ...
endswitch
endfor我刚刚把这个问题变成了一个完整的octave程序,可以用其他函数调用替换plot功能。重要的是,我从1:1中添加了一个1:1循环并使用break,但这当然只是一个技巧!
switch在octave中的常见突破是什么?
发布于 2014-08-12 13:12:00
也许我忽略了你问题的重点,但break只适用于循环。这就是你想要做的:
switch (dim)
case 2
% Print points as dots
plot(P(1,:),P(2,:),'.');
if (plot_mean)
hold on
% Print mean values as red circles
plot(mu(1,:),mu(2,:),'or');
end
case 3否则,听起来就像是在尝试实现一个"goto"-like语句,这是一种糟糕的做法。而是重构您的代码(如上面所示)。
我认为这是不可能的,因为正如您的黑客所指出的那样,您可以从包含break的循环中获取其中一种情况下的switch。这是可能的,因为Octave/Matlab的行为与C不同。这些论坛上的帖子似乎同意,但这几乎不是决定性的证据:
但是,要回答您的问题,什么是从Octave中切换的正常方式,我想说的是,通常的方法是将代码封装在if语句中。
https://stackoverflow.com/questions/25265124
复制相似问题