Info

This question is closed. Reopen it to edit or answer.

Looping past the end of an array - I don't see how?

1 view (last 30 days)
Steve D
Steve D on 18 Aug 2011
Closed: MATLAB Answer Bot on 20 Aug 2021
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

Answers (5)

Rick Rosson
Rick Rosson on 18 Aug 2011
Please format your code. If you don't know how, please review the following:
Thanks!
Rick

Steve D
Steve D on 18 Aug 2011
Is the problem that the array indexes from 0 instead of 1?

Rick Rosson
Rick Rosson on 18 Aug 2011
Big improvement. Thanks!

Rick Rosson
Rick Rosson on 18 Aug 2011
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 Comments
Fangjun Jiang
Fangjun Jiang on 18 Aug 2011
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)

Steve D
Steve D on 18 Aug 2011
Thanks for your suggestions. It looks like matlab evaluates the while conditions in order such that the i that is over the limit, (stim(i)<82), is used before it is checked, && (i<640).
I reversed the order, and the problem went away.
3 Cheers, Steve

This question is closed.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!