フィルターのクリア

Info

この質問は閉じられています。 編集または回答するには再度開いてください。

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

1 回表示 (過去 30 日間)
Steve D
Steve D 2011 年 8 月 18 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
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

回答 (5 件)

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

Steve D
Steve D 2011 年 8 月 18 日
Is the problem that the array indexes from 0 instead of 1?

Rick Rosson
Rick Rosson 2011 年 8 月 18 日
Big improvement. Thanks!

Rick Rosson
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 件のコメント
bym
bym 2011 年 8 月 18 日
1 to 640
Fangjun Jiang
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)

Steve D
Steve D 2011 年 8 月 18 日
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

この質問は閉じられています。

Community Treasure Hunt

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

Start Hunting!

Translated by