switch/case 语句未正确评估

switch/case statement not evaluating properly

我有这个 for 循环和 switch 语句,它循环遍历矩阵的特定行,评估该元素中的任何内容,并基于此更新同一矩阵的另一行。我的问题是它似乎没有正确评估。进行一些手动调试时,它似乎会定期跳过某些条件并且不会在其中执行命令(尽管不是所有时间)而且我无法弄清楚为什么...... 无论如何,这是代码,对不起,这是整个功能。当我将它拆分成一个示例矩阵然后切换 statment/for 循环时,它似乎起作用了。它只是不能作为一个整体工作(我需要它以这种方式工作,即随机化)

ptpschedule = zeros(3, ntrials);
silenttrialpercent = 0.25;
noSilentTrials = ntrials*silenttrialpercent;
ptpschedule(1,1:ntrials) =  1;
ptpschedule(1,1:noSilentTrials) = 0;
ptpschedule(1,:) = ptpschedule(1,randperm(ntrials));
V = 4; % number of different time points 
x = 0.8; %window for beeps
a = x/V % spacing between each beep to fill in an x second window, in this case 200ms. 
ind = ptpschedule(1,:)>0; % logical index of positive values in the first row
n = nnz(ind);
vals = mod(0.05:a:n-1, x); % values to be randomly thrown in. 
vals(vals==0) = x;
    %This guarantees the same number of each value if n is a multiple of V
ptpschedule(2,ind) = vals(randperm(n)); % fill values in second row in random order

for i = 1:length(ptpschedule)
        switch ptpschedule(2,i)
            case 0.05
                ptpschedule(3,i) = 1
            case 0.25
                ptpschedule(3,i) = 2
            case 0.45
                ptpschedule(3,i) = 3
            case 0.65
                ptpschedule(3,i) = 4
        end

end

有时它会正确计算并输入相应的数字,但有时它不会正确地计算并只是将其保留为 0(但是,当 ptpschedule(1,i) == 0 它应该将相应的值保留在第三行为 0).

10 次试验的期望输出为:

[0.00, 0.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00;
 0.00, 0.00, 0.05, 0.45, 0.05, 0.65, 0.45, 0.25, 0.25, 0.65;
 0.00, 0.00, 1.00, 3.00, 1.00, 4.00, 3.00,  2.00, 2.00, 4.00]

谢谢!

马丁

您的 switch/case 结构中存在浮点问题,但由于您的情况非常简单,您可以使用 round:

轻松修复它

Y = round(X) rounds each element of X to the nearest integer.

根据整数做出切换决定。

for i = 1:length(ptpschedule)
    switch round( ptpschedule(2,i)*100 )
        case 5
            ptpschedule(3,i) = 1
        case 25
            ptpschedule(3,i) = 2
        case 45
            ptpschedule(3,i) = 3
        case 65
            ptpschedule(3,i) = 4
    end
end