Info
此问题已关闭。 请重新打开它进行编辑或回答。
Looping past the end of an array - I don't see how?
1 次查看(过去 30 天)
显示 更早的评论
When I run this code, it runs K times and bombs (depending on how the array was randomized) due to an array index out of bounds for the while loop on line 19. But I thought I prevented that with the preceeding 4 statements. ??
k=0;
while 1==1
novel=1:80;
novel=novel(randperm(80));
targ=ones(80)*81;
freq=ones(480)*82;
stim=1:640;
stim(1:80)=novel(1:80);
stim(81:160)=targ(1:80) ;
stim(161:640)=freq(1:480);
stim=stim(randperm(640)); % Is this truely a random perm ?
% Scan looking for 2 n/t in a row, move the 2nd further along
% and replace with a frequent.
si=1;
while si<639
if (stim(si)<81) && (stim(si+1)<81) && (si<639)
i=si+2;
while (stim(i)<82) && (i<641) i=i+1; end
if (i<641) && (stim(i)==82)
stim(i)=stim(si+1); %push the right one right
stim(si+1)=82; % replace with a frequent
si=si+2;
end
end
si=si+1;
end
% Now repeat the process scanning in the opposite direction
% in case n/t pairs were bunched up at the end of the vector.
si=640;
while si>2
if (stim(si)<81) && (stim(si-1)<81) && (si>2)
i=si-2;
while( stim(i)<82) && (i>2) i=i-1; end
if (i>0) && (stim(i)==82)
stim(i)=stim(si-1); % push the left one left
stim(si-1)=82; % replace with a frequent
si=si-2;
end
end
si=si-1;
end
display('First 40');
stim(1:40)
display('Last 40');
stim(601:640)
k=k+1;
k
end
0 个评论
回答(5 个)
Rick Rosson
2011-8-18
Have you tried setting a break-point on the offending line of code, and then examining the values of the relevant variables in debug mode?
3 个评论
Fangjun Jiang
2011-8-18
MATLAB uses 1-based index. change your number from 641 to 640 avoided the error but not sure if the algorithm is correct.
while (stim(i)<82) && (i<640)
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!