0

When I am executing this function:

function generate(x)

  for k=1:257
  x= round(rand*9);
  vet = x*ones(1,16);
  i= round(rand*length(vet));
  val= round(rand*257);
  vet(i)=val
  vet= dec2hex (vet)
  endfor

endfunction

I found this error that I don't understand:

error: generate: subscript indices must be either positive integers less than 2^31 or logicals
error: called from
    generate at line 8 column 9

I would be very grateful if you could help me please.

Adriaan
  • 17,741
  • 7
  • 42
  • 75

1 Answers1

3

I used MATLAB R2015a to replicate the behaviour. The error text is slightly different, but the code essentials are the same as octave

round(something) can generate 0. When I run your code it hits a 0 every once in a while and crashes with

Attempted to access vet(0); index must be a positive integer or logical.

because 0 is not a positive integer, nor is it a logical in the case of the other indices being positive integers. To fix it I suggest changing all zeros in ii to 1:

for k=1:257
  x= round(rand*9);
  vet = x*ones(1,16);
  ii= round(rand*length(vet));
  ii(ii==0)=1;
  val= round(rand*257);
  vet(ii)=val;
  vet= dec2hex (vet);
end % endfor for octave

Note that I changed i to ii, as i is a built-in function

An alternative would be to not use round, but ceil. That way it always round to positive infinity, i.e. it will never hit 0 when using only positive numbers:

for k=1:257
  x= round(rand*9);
  vet = x*ones(1,16);
  ii= ceil(rand*length(vet));
  val= round(rand*257);
  vet(ii)=val;
  vet= dec2hex (vet);
end % endfor for octave
Community
  • 1
  • 1
Adriaan
  • 17,741
  • 7
  • 42
  • 75