Doug's MATLAB Video Tutorials

September 24th, 2010

Deleting in a loop

Ever try to delete some values in a vector by looping through from beginning to end? I have, and failed because the indexing got confused as the vector changed. Here is one solution to that class of problems.

5 Responses to “Deleting in a loop”

  1. k replied on :
    n=10;
    a=rand(1,n);
    a(rand(1,n)<0.1)=[];
    
  2. Oliver Woodford replied on :

    Is deleting elements in a loop a good idea? Won’t it reallocate memory every iteration, and therefore slow things down?

  3. dhull replied on :

    @k

    If you can vectorize this kind of operation, then your code is a good idea. The premise of this video, stated at the beginning, was that the operation that decides if something should be deleted only works on scalars. That is why I used a for loop (pretending my silly filter could not be vectorized).

    @Oliver

    For ‘small’ cases the reallocation effect would be negligible. It is a constant balance of simplicity vs optimality.

    -Doug

  4. Ed replied on :

    counting backwards seems a lot easier than using a while loop, which is what I usually have done in the past.

    i = 1;
    while i <= length(a)
        if isDeleteMe(a(i))
            a(i) = [];
        else
            i = i + 1;
        end
    end
    
  5. dhull replied on :

    @Ed,

    There are many, many ways of solving this and similar problems in MATLAB. They all have advantages and disadvantages. The more techniques you are aware of, the better. Some, like the flawed one I presented, are never the best (but tempting to try). I can see yours would be good if somewhere in the loop the vector could have more data postpended to it!

    Thanks,
    Doug

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


MathWorks

Doug Hull is a proud MathWorker who is on a mission to help you with MATLAB.

Doug's picture

These postings are the author's and don't necessarily represent the opinions of The MathWorks.