MATLAB: I don’t understand why the matrix dimensions are exceeded

dimensionsexceedsmatrix

A= zeros(3,10);
A(1,:)=[1:10];
B=.5+rand(1,10)*.4;
A(2,:,:)=B;
C=round(1+rand(1,10)*7);
A(3,:,:)= C;
A
team_A= zeros(3,5);
team_B= zeros(3,5);
for d=[1:1:10]
if rem(d,2)==1;
for e=[1:1:10]
if A(2,e)== max(B)
p=e;
team_A(:,2,:)=A(:,p,:);
A(:,p)=[];
end
end
elseif rem(d,2)==0
for f=[1:1:10]
if A(2,f)== max(C);
i=f;
team_B(:,2,:)=A(:,i,:);
A(:,i)=[];
end
end
end
end
Index exceeds matrix dimensions.
Error in JAS_HW4 (line 14)
if A(2,e)== max(B)

Best Answer

I believe I see the problem.
In these lines:
A(:,p)=[];
and
A(:,i)=[];
you’re shortening ‘A’ by one column. If you want empty values in your array, you either have to set them equal to NaN (in a numeric array), or if you decide to use a cell array, it will tolerate empty entries.
I would change them both to:
A(:,p)=NaN;
and
A(:,i)=NaN;
respectively. Your code will run with that change without throwing the error, but you may have more work to do to make it give you the results you want.