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