开关/外壳内部环路不能正常工作

时间:2014-04-19 15:29:26

标签: matlab for-loop matrix switch-statement

我需要检查矩阵的每个元素,看它是否是特定的。 我必须为这段代码使用switch / case。 我有这样的矢量:

COUNTER=[counterA counterB counterC counterWaste]

我试过了:

for n=1:size(COUNTER,2)
   switch COUNTER(1,n)
       case counterA
          disp(['counterA is ' , num2str(counterA)])
       case counterB
          disp(['counterB is ' , num2str(counterB)])
       case counterC
          disp(['counterC is ' , num2str(counterC)])
       case counterWaste
          disp(['counterWaste is ' , num2str(counterWaste)])
    end
end

counterA& counterB&反C和counterWaste是一些包含随机数的变量。 它给出了正确的数字,因为我已经知道每个计数器变量的正确数量,但字符串不正确。例如,一旦它给出

counterA is 1
counterB is 2
counterA is 1
counterB is 2

下次

counterA is 4
counterB is 1
counterB is 1
counterWaste is 0

和......

我不知道问题出在哪里。谁有任何想法?

3 个答案:

答案 0 :(得分:1)

我认为问题在于你有

COUNTER=[counterA counterB counterC counterWaste]

但正如你所说,counterA counterB counterC counterWaste是随机值,所以在你的第一个例子中

counterA is 1
counterB is 2
counterA is 1
counterB is 2

你有,我想COUNTER=[1 2 1 2] 你在COUNTER里面的值上使用swich case,但是你在这里有counterA = counterC = 1,所以你的switch case就像那样使用

for n=1:size(COUNTER,2)
   switch COUNTER(1,n)
       case counterA  % counterA = counterC = 1 go there
          disp(['counterA is ' , num2str(counterA)])
       case counterB  % counterB = counterWaste = 2 go there
          disp(['counterB is ' , num2str(counterB)])
       case counterC  % counterC = 1 but never used because counterC go to case counterA
          disp(['counterC is ' , num2str(counterC)])
       case counterWaste % same as case counterC
          disp(['counterWaste is ' , num2str(counterWaste)])
    end
end

实际上我认为每个 case 应该有不同的值(case正在评估值,而不是var名称)因为如果两个案例具有相同的值(它这里是可能的,因为你的值是随机的)只评估第一个(:

问题是相同的:

counterA is 4
counterB is 1
counterB is 1
counterWaste is 0

您有COUNTER=[4 1 1 0]因此case counterC永远不会被评估,因为case counterBcounterBcounterC。 但我可能错了,很久没有使用MatLab

我认为这应该有效:

for n=1:size(COUNTER,2)
   switch n
       case 1  
          disp(['counterA is ' , num2str(counterA)])
       case 2  
          disp(['counterB is ' , num2str(counterB)])
       case 3  
          disp(['counterC is ' , num2str(counterC)])
       case 4 
          disp(['counterWaste is ' , num2str(counterWaste)])
    end
end

请注意,还有很多其他方法可以做到这一点。这一个很复杂,没有什么^^

答案 1 :(得分:1)

你是在滥用案件,朋友。您尝试按变量名切换,但变量名只是指向该变量所持有的值。试试这个:

for n=1:size(COUNTER,2)
   switch n
       case 1
          disp(['counterA is ' , num2str(counterA)])
       case 2
          disp(['counterB is ' , num2str(counterB)])
       case 3
          disp(['counterC is ' , num2str(counterC)])
       case 4
          disp(['counterWaste is ' , num2str(counterWaste)])
    end
end

请注意,我按照可预测的行为进行切换。祝你好运,编码愉快。

编辑:为了澄清,我不认为这是最好的解决方案,Raf更好。它只是满足使用开关/案例的提问者限制。

答案 2 :(得分:1)

您可以删除forswitch语句,并按照这样做吗?

disp(['counterA is ' , num2str(COUNTER(1,1))]);
disp(['counterB is ' , num2str(COUNTER(1,2))]);
disp(['counterC is ' , num2str(COUNTER(1,3))]);
disp(['counterWaste is ' , num2str(COUNTER(1,4))]);