I have an array a and a new_elem.
- If
new_elemis smaller than any existing member ina, then it is not allowed to be added intoa. - On the contrary, if
new_elemis larger than any existing member ina, then it is allowed to be added intoa, and those existing elements smaller thannew_elemhave to be kicked out.
I implemented this as follows.
a = [a new_elem]; % add in first
for idx = 1:1:numel(a)-1
% new_elem < some existing member
if a(idx) > new_elem
a = a(1:end-1); % kick new_elem out
break;
% new_elem > some existing member
elseif a(idx) < new_elem
a(a==a(idx)) = []; % kick that exisiting member out
end
end
The snippet works when new_elem is smaller, e.g.,
new_elem = 4;
a = [5 5 5 5 5];
It fails with the error Index exceeds matrix dimensions.
in the other cases, e.g.,
new_elem = 6;
a = [5 5 5 5 5];
I understand that the problem is once we kick out an existing element, the size of a changes, and hence, we will have trouble indexing the final element, since numel(a) has been evaluated before the loop starts.
How could I fix it?
P.S.: This is a simplified version of my problem and actually involves a lot more. So please kindly do not subversively modify the algorithm.