# How can I fix "Index in position 2 exceeds array bounds" in for loop/ if statements?

6 views (last 30 days)
Andrew Stark on 6 Nov 2020
Commented: Andrew Stark on 6 Nov 2020
W=cell(p,1);
for j=1:(p-1);
w=A(index(j):index(j+1)-2);
W{j}=w;
end
W2=cell(p,1);
for j=1:(p-1);
w2=A(index(j):index(j+1)-2);
W2{j}=w2;
end
Z=cell(p,1);
for ii=1:p
P1=W{ii,1};
Z{ii,1}=P1(3:3:end);
end
for ii=1:p
P2=Z{ii,1};
if P2(end,1)>0
W2(ii,1)={[]};
end
end
I am getting the error "Index in position 2 exceeds array bounds" on the line if P2(end,1)>0
The W2 matrix looks how I want it to look I just dont know how to stop it from producing an error.

Show 1 older comment
Sindar on 6 Nov 2020
Specifically, it would be useful to know the following at the time of the error:
• the value of ii
• the size of P2 (my guess is that it is an empty array)
• the size of W{ii,1}
Extra question: do you use Z for anything later, or is it purely a temporary variable in this chunk?
Andrew Stark on 6 Nov 2020
at the time of error
ii=10,000 (final p value)
P2 is an empty array
W2 is a 10000x1 cell matrix
Andrew Stark on 6 Nov 2020
Currently it is a temporary variable but eventually I will use Z later! Thank you so much for your help!

Sindar on 6 Nov 2020
Okay, I believe this code is equivalent to what you have, cleaner and without the error
% pre-allocate with cell arrays of []
W=cell(p,1);
W2=cell(p,1);
Z=cell(p,1);
for ii=1:p
% for all but the last index,
% load in part of A
if ii<p
P1=A(index(ii):(index(ii+1)-2));
% but, we want P1 defined
else
P1=[];
end
W{ii}=P1;
% be explicit about copying W
% there may also be internal Matlab tricks that save some memory with this way
W2(ii)=W(ii);
Z{ii}=P1(3:3:end);
if ~isempty(P1) && Z{ii}(end)>0
W2(ii)={[]};
end
end
A few tricks:
• instead of separate for loops, combine into one
• in the last, extra iteration for W1/W2, explicitly leave the cell empty (you may want something else here)
• avoid packing and unpacking the same cell data
• you can index into a cell of Z, avoiding the P2 temporary variable
• isempty check avoids the original error. In this case, the cell will already be empty, anyway

#### 1 Comment

Andrew Stark on 6 Nov 2020
That works great! Thank you! I guess the last value/index in the for loop was causing the problem

VBBV on 6 Nov 2020
Since P2 and W2 are both cell arrays use curly braces
%if true
% code
%end
for ii=1:p
P2=Z{ii,1};
if P2{end,1}>0
W2{ii,1}={[]};
end
end

VBBV on 6 Nov 2020
%if true
% code
%end
for ii=1:p
P2=Z{ii,1};
if P2(end,1)>0
W2{ii,1}={[]};
end
end
Can you check if P2 is row vector or column vector ?
If its row vector then try
if P2(1,end) > 0
Sindar on 6 Nov 2020
That's not it. The issue is that P2 is sometimes empy. Even this throws an error:
x=[];
x(end,end)
VBBV on 6 Nov 2020
@ Sindar, your'e right
It might be that P2 is just empty