MATLAB - Loop through a size-variant array? -


i have array a , new_elem.

  • if new_elem smaller existing member in a, not allowed added a.
  • on contrary, if new_elem larger existing member in a, allowed added a, and existing elements smaller new_elem have kicked out.

i implemented follows.

a = [a new_elem]; % add in first idx = 1:1:numel(a)-1     % new_elem < existing member     if a(idx) > new_elem         = a(1:end-1); % kick new_elem out         break;     % new_elem > existing member         elseif a(idx) < new_elem         a(a==a(idx)) = []; % kick exisiting member out     end end 

the snippet works when new_elem smaller, e.g.,

new_elem = 4; = [5 5 5 5 5]; 

it fails error index exceeds matrix dimensions. in other cases, e.g.,

new_elem = 6; = [5 5 5 5 5]; 

i understand problem once kick out existing element, size of a changes, , hence, have trouble indexing final element, since numel(a) has been evaluated before loop starts.

how fix it?

p.s.: simplified version of problem , involves lot more. please kindly not subversively modify algorithm.

why not list/array of elements in a less new_elem , make decision based on that, avoiding loops altogether?

% list of indices of elements in less new_elem minidcs = find(a<new_elem);  % if length of list less length of a, there @ % least 1 element in greater new_elem - add new_elem % if lengths identical if length(minidcs) == length(a)     % remove elements of less new_elem     a(minidcs) = [];      % add new_elem     = [a new_elem]; end 

this works not sure if compatible intended code dependent upon order of elements in a: new_elem may smaller @ least 1 element in a, element may not encountered several iterations of loop, other elements of a might removed before make decision new_elem should not added.

if order important, use while loop instead

a = [a new_elem]; % add in first idx = 1; n   = length(a); while idx < n     % new_elem < existing member     if a(idx) > new_elem         = a(1:end-1); % kick new_elem out         break;     % new_elem > existing member         elseif a(idx) < new_elem         a(idx) = []; % kick exisiting member out         n = n-1;     else         idx=idx+1;     end end 

the above similar have - need keep track of number of elements in list (which adjusted whenever remove element) , need increment index idx when don't remove element. , rather removing elements less new_elem in one-shot, handle them on case-by-case basis (so a(idx) = []; rather a(a==a(idx)) = [];).


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -