MATLAB: How do i change the length of a vector in a for loop without it causing an index out of bounds error

for loopMATLABvector

for k = length(otherHand)
for p = 1:length(possible)
if otherHand(k) == possible(p)
currentHand(end+1) = otherHand(k);
otherHand(k) = [];
end
end
end
The length of otherHand starts at 5, but is shortened within the if statement.
If this is not possible, is there a way i can transfer one element of one vector to the end of another?
Thanks in advance.

Best Answer

You can't delete elements of an array while you're iterating over it unless you work in reverse and are extremely careful.
However, you need to learn to use matlab as it's meant to:
ismatch = ismember(otherhand, possible);
currenthand = otherhand(ismatch);
otherhand = otherhand(~ismatch);
No loop needed and much simpler and understandable code.