Search code examples
arraysmatlabruntime-errorindexoutofboundsexception

Matlab index out of range


I seem to be getting an index out of range error when I run the program. It seems to occur on line 19 and relates to the vec2 variable. I don't understand why this is happening, however, because vec2 is initialized the same way as vec. Any help would be appreciated. Thank you!!

N = 6;
vec2 = ones(1,N);
vec = ones(1,N) * -1;


for i = 1:N
  num = input('Enter an integer: ');

  if num >= 0
      vec(i) = num;
  else
      vec2(i) = num;
  end

  if sign(vec(i)) == -1
      vec(i) = [];
  end

  if sign(vec2(i)) == 1
      vec2(i) = [];
  end
end

save pos.dat vec -ascii;
save neg.dat vec2 -ascii;

Solution

  • The problem you are facing could be illustrated as follows:

    vec = [1, 2, 3];% assuming a given vector vec, length = 3
    vec(2) = 5; % no problem 
    vec = [1, 5, 3];
    vec(2) = [];% vec length is 2
    vec = [1, 3];
    vec(3) = 10; % not allowed 
    %% index out of range since the length of vec is 2
    

    Alternative

    • Instead of removing the cells at first place
    • fill them with nan
    • then remove all cell with nan

    The code is as follows

    N = 6;
    vec2 = ones(1,N);
    vec = ones(1,N) * -1;
    
    
    for i = 1:N
      num = input('Enter an integer: ');
    
      if num >= 0
          vec(i) = num;
      else
          vec2(i) = num;
      end
    
      if sign(vec(i)) == -1
          vec(i) = nan;
      end
    
      if sign(vec2(i)) == 1
          vec2(i) = nan;
      end
    end
    %% remove nan
    vec = vec(~isnan(vec));
    vec2 = vec2(~isnan(vec2));