MATLAB: Error:index must be a positive integer or logical.

index must be a positive integer or logical.

Anybody can help me whats wrong with my code please. I am constantly getting this error Attempted to access f(1.99); index must be a positive integer or logical.
Error in extreme (line 22) y2=f(x2);

Best Answer

You have created (somewhere) a variable f. f is a scalar, a vector or an array.
Where is the 1.99'th element of that array? When did you create that element? The fact is, you cannot stuff something into the 1.99'th place in memory. There is no such place. Yet you have tried to access that memory element.
Since this is clearly impossible, MATLAB returns an error. It told you that your index must be a positive integer, or a logical (boolean) vector. However x2 is apparently the floating point number 1.99. How it got to be that is by your own design, since it was created by your coding.
If you are constantly getting that error, then you need not to try to index variables with real numbers. Perhaps you think of f as a function. It is not. It is a variable, at least as you have created it.
Related Question