I am trying to remove elements from a vector in Matlab by some condition. For example, I want to delete all even numbers.

a = [1 2 3 4 5 6]; for i = 1:numel(a) if (mod(a(i), 2)) == 0 a(i) = []; end end 

At the same time I receive "Index exceeds matrix dimensions." . It looks like the cycle continues to spin to the original length of the vector, despite the fact that it has decreased. How to deal with it?

But to be completely accurate, I want to write this cycle:

 function [centers, rads, metrics] = ... DeleteOverlapCircles(centers, rads, metrics) for i = 1:(length(metrics) - 1) for j = (i + 1):length(metrics) minRad = min([rads(i), rads(j)]); maxRad = max([rads(i), rads(j)]); if pdist2(centers(i), centers(j)) < maxRad + 1 / 2 * minRad metrics(j) = []; centers(j) = []; rads(j) = []; end end end end 

The question was resolved as follows:

 function [centers, rads, metrics] = ... DeleteOverlapCircles(centers, rads, metrics) for i = (length(metrics) - 1):-1:1 for j = (i - 1):-1:1 minRad = min([rads(i), rads(j)]); maxRad = max([rads(i), rads(j)]); if pdist2(centers(i, :), centers(j, :)) ... < maxRad + 1 / 2 * minRad centers(i, :) = []; rads(i) = []; metrics(i, :) = []; break; end end end end 

But I am not ready to believe that there is no more obvious and beautiful solution.

    4 answers 4

    The for loop is not intended for conditions that vary within a loop. That is, if there is a condition

     for i = 1:numel(a) 

    the numel(a) value will be calculated only once, when entering the cycle.

    If the final value changes, you need a while :

     a = [1 2 3 4 4 5 6]; i = 1; while i <= numel(a) if (mod(a(i), 2)) == 0 a(i) = []; else i = i+1; end end 

    I note that the loop variable does not increase in the case of deletion of an element, since in this case other elements are shifted.

    (But going from the end to the beginning, as you did, is actually easier.)

      It is possible on the contrary to save the necessary elements in a separate array.

       a = [1 2 3 4 5 6]; b = []; for i = 1:numel(a) if (mod(a(i), 2)) ~= 0 b(end + 1) = a[i]; end end a = b; 

      Or short:

       b = find (~mod (a, 2)) 
      • In this example, this method really looks normal. But it seems to me that if I try to do what I really want, it will turn out very ugly. The code from the real task led to the issue. - Vladimir

      Delete the specified element numbers from the array:

       aaa = 1:1:10; % Исходные индексы bbb = 1:2:10; % Индексы, которые следует удалить ccc = aaa; ccc(bbb) = 0; ccc = (ccc > 0); % Исключенные индексы 

        Laconic of all

         a = [1 2 3 4 4 5 6]; a=a(mod(a, 2)==0);