-2

I got exactly this error:

Attempted to access E(3,1); index must be a positive integer or logical. 

But the index is E(3,1), those numbers are both positive. What is going on?

for t=T:0.2:4
    for i=1:N
        % D = D +1
        x = randi(Nsamples,1,1);
        if(x==1)
            Etemp = E(t*5,i) - S(x)*S(x+1) + (-S(x))*S(x+1);
        elseif(x==Nsamples)
            Etemp = E(t*5,i) - S(x)*S(x-1) + (-S(x))*S(x-1);
        else
            %********************* This is the error line
            Etemp = E(t*5,i) - (S(x-1)*S(x)+S(x)*S(x+1))+ (S(x-1)*(-S(x))+(-S(x))*S(x+1));
        end
    end
end
sco1
  • 12,154
  • 5
  • 26
  • 48
Bekromoularo
  • 99
  • 11
  • 3
    `t*5` is not an integer, it's a float. See: [Why is 24.0000 not equal to 24.0000 in MATLAB?](http://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab) – sco1 Dec 28 '16 at 13:52
  • Then why the error occurs only when t*5 = 3(E(3,1))? and not when the value is 2 (E(2,1))? – Bekromoularo Dec 28 '16 at 14:04
  • It's a coincidence. – sco1 Dec 28 '16 at 14:06
  • @Bekromoularo you can try wrapping `t*5` with `round` (i.e. `E(round(t*5), i)`. Also, you probably shouldn't use `i` as a loop variable :) **edit**: just noticed you don't use the literal value of `t` in computations - so it would be best to just make sure `t` is always an integer right from the start (multiply he `for` arguments by `5` and `round`)... – Dev-iL Dec 28 '16 at 15:37

1 Answers1

0

3 index in E(3,1) may not exactly be an integer. In your case, index row index 3 is generated by multiplying t*5 i.e. 0.6*5 (if t=0.6). It does not guarantee it to be an integer.

In a high accuracy check on generated index value 3, you will find that it is off from the exact integer 3 by 1 bit or so at its least significant end.

Therefore, while indexing E(3,1), 3 is not perceived as an integer.

In cases where you generate the index by multiplying with a decimal, make sure to convert it to int before using it for indexing such as round(t*0.5) or int8(t*0.5).

Or all together avoid index which are generated by multiplying the decimals.

hsuyaa
  • 79
  • 1
  • 1
  • 8