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.
By
Doug Hull
Doug first used MATLAB in 1994, could not figure it out until he got some help in 1995. He is now dedicated to making sure that no one else wastes a year of their life not knowing MATLAB like he did.
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.
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
About
Doug Hull is a proud MathWorker who is on a mission to help you with MATLAB.
Is deleting elements in a loop a good idea? Won’t it reallocate memory every iteration, and therefore slow things down?
@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
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@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