MATLAB: Randomization one of four triangles – Error: index out of bounds

index out of boundsrandomizationshape

Here is my code:
downtri = [50 0;0 50;-50 0];
uptri = [50 0;0 -50;-50 0];
righttri = [0 50;0 -50;50 0];
lefttri = [0 50;0 -50;-50 0];
arrarray = [downtri;uptri:lefttri:righttri];
arrdx1 = randi(4,1,1);
arrow1 = arrarray(arrdx1,:);
arrdx2 = randi(4,1,1);
while ismember(arrdx2, arrdx1)
arrdx2 = randi(4,1,1);
end
arrow2 = arrarray(arrdx2,:);
arrdx3 = randi(4,1,1);
while ismember(arrdx3, [arrdx1,arrdx2])
arrdx3 = randi(4,1,1);
end
arrow3 = arrarray(arrdx3,:);
arrdx4 = randi(4,1,1);
while ismember(arrdx4, [arrdx1,arrdx2,arrdx3])
arrdx4 = randi(4,1,1);
end
arrow4 = arrarray(arrdx4,:);
So the above is meant to randomize shape of a triangle with 4 different shape possibilities (it works great with randomizing color). However, when I try to randomize triangles I get this error message: "Attempted to access arrarray(4,:); index out of bounds because size(arrarray)=[3,2]. I think it means that basically the shape of the triangle won't fit into the matrix, but I'm not sure how to fix it.
Please help, 🙁 🙁 🙁

Best Answer

Change
arrarray = [downtri;uptri:lefttri:righttri];
to
arrarray = [downtri;uptri;lefttri;righttri];
Warning: your triangles are all 3 x 2, and you are trying to store several of them in one array, but then you are accessing by row number rather than by triangle number.
Side note:
Have you considered replacing your code
arrdx4 = randi(4,1,1);
while ismember(arrdx4, [arrdx1,arrdx2,arrdx3])
arrdx4 = randi(4,1,1);
end
with
arrdx4 = setdiff(1:4, [arrdx1,arrdx2,arrdx3]);
?