0

I am triying to write a code which automatically checks the input data with a bounded range and removes the ones outside this boundary. I have written the following code:

LANDA_E_4=landa;
 for i=1:m
    if i>m
        break
    elseif LANDA_T_2(i)<0.2021e+03 || LANDA_T_2(i)>1.3317e+03
        LANDA_T_2(i)=[];
        i=i-1;
    end

The problem here is that the "i" does not update within the loop. Consider the first element is not within the range, so it gets removed. now the loop should check the new first element which is the previous second element (before removing the first one) but the "i" whitin the loop is still 2. I can't update "i".

Thank you in advance

1 Answers1

1

The problem with your approach is that at each iteration of the loop i gets set to the number of that iteration, even if you modify it in between. (And besides taht it is bad practice to use i as a variable, as by default it is set to the imaginar unit 1i.) To make your approach work you would have to use a while loop.

But it is even easier to use logical indexing instead and avoid loops like so:

% bougs data
m = 100;
LANDA_T_2=rand(1, m)*2e3;
% remove loops
LANDA_T_2(LANDA_T_2<0.2021e+03 | LANDA_T_2>1.3317e+03) = [];
disp(size(LANDA_T_2))

Try it online!

flawr
  • 10,814
  • 3
  • 41
  • 71