Reputation: 51
I have this for loop and switch statement which loops through a particular row of a matrix, evaluates whatever is in that element and the updates the another row of the same matrix based upon that. My problem is that it doesn't seem to be evaluating properly. Doing some manual debugging it seems to periodically skip over certain conditions and not execute the command within (though not all the time) and I can't figure out why... Anyway, here's the code, sorry that it's the whole function. When I split it into an example matrix and then the switch statment/for loop it seemed to work. It just doesn't work as a whole (and I need it to work in this manner i.e. randomised)
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
Sometimes it evaluates correctly and puts in the corresponding number, but other times it doesn't and just leaves it at 0 (though, when ptpschedule(1,i) == 0 it should leave the corresponding value in the third row as 0).
A desired output for 10 trials would be:
[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]
Thanks!
Martin
Upvotes: 1
Views: 69
Reputation: 25232
There is a floating point issue in your switch/case
structure, but as your cases are quite simple you can easily fix it by using round
:
Y = round(X)
rounds each element of X to the nearest integer.
to base the switch decisions on integers.
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
Upvotes: 2