field101
field101

Reputation: 11

Matlab not accepting whole number as index

I am using a while loop with an index t starting from 1 and increasing with each loop. I'm having problems with this index in the following bit of code within the loop:

dt = 100000^(-1);
t = 1;
equi = false;
while equi==false

 ***some code that populates the arrays S(t) and I(t)*** 

t=t+1;   
if (t>2/dt)
        n = [S(t) I(t)];
        np = [S(t-1/dt) I(t-1/dt)];
        if sum((n-np).^2)<1e-5
            equi=true;
        end
end

First, the code in the "if" statement is accessed at t==200000 instead of at t==200001.

Second, the expression S(t-1/dt) results in the error message "Subscript indices must either be real positive integers or logicals", even though (t-1/dt) is whole and equals 1.0000e+005 . I guess I can solve this using "round", but this worked before and suddenly doesn't work and I'd like to figure out why. Thanks!

Upvotes: 0

Views: 121

Answers (3)

Hugo
Hugo

Reputation: 159

The statement

S(t-1/dt)

can be replaced by

S(uint32(t-1/dt))

And similarly for I. Also you might want to save 1/dt hardcoded as 100000 as suggested above. I reckon this will improve the comparison.

Upvotes: 0

mbauman
mbauman

Reputation: 31352

Matlab is lying to you. You're running into floating point inaccuracies and Matlab does not have an honest printing policy. Try printing the numbers with full precision:

dt = 100000^(-1);
t = 200000;
fprintf('2/dt == %.12f\n',2/dt) % 199999.999999999971
fprintf('t - 1/dt == %.12f\n',t - 1/dt) % 100000.000000000015

While powers of 10 are very nice for us to type and read, 1e-5 (your dt) cannot be represented exactly as a floating point number. That's why your resulting calculations aren't coming out as even integers.

Upvotes: 0

abcd
abcd

Reputation: 42225

the expression S(t-1/dt) results in the error message "Subscript indices must either be real positive integers or logicals", even though (t-1/dt) is whole and equals 1.0000e+005

Is it really? ;)

mod(200000 - 1/dt, 1)
%ans = 1.455191522836685e-11

Your index is not an integer. This is one of the things to be aware of when working with floating point arithmetic. I suggest reading this excellent resource: "What every computer scientist should know about floating-point Arithmetic".

You can either use round as you did, or store 1/dt as a separate variable (many options exist).

Upvotes: 3

Related Questions