Array indices must be positive integers or logical values

N = zeros(1,20);
for ii = 0.01:0.01:2
j = ii*100;
N(j) = ii*10;
end
This is a sample part of another code.I'm getting the error 'Array indices must be positive integers or logical values'. If i change the for loop as
for ii= 0.25:0.25:2
j = ii*4;
N(j) = ii*10;
end
then the result is being displayed. Please let me know what is the error.!!

답변 (1개)

Jan
Jan 2022년 2월 18일
편집: Jan 2022년 2월 18일
Welcome to the world of numerical maths. This is a frequently ask question, see: FAQ: Why is 0.3-0.2-0.1 not equal to 0?
Trust Matlab's error message and use the debugger to find the problem: Type this in the command window:
dbstop if error
Start the function again. When Matlab stops at the error, check the value of the index:
format long g
j
rem(j, 1)
Another version of this well known effect:
any(0:0.1:1) == 0.3 % FALSE!!!
This happens, because Matlab uses floating point values in double format in the IEEE754 format. Most decimal floating point numbers to not have an exact representation in the binary format. So is the binary IEEE754 format a bad choice? No, because the other way around is true also: Most binary values do not have an exact representation in decimal format also.
You have to consider this and care for safe limit:
any(abs((0:0.1:1) - 0.3) < 100 * eps) % TRUE
Or in your code:
N(round(j)) = ii*10;
The save way is never to use the result of floating point operations as indices:
data = 0.01:0.01:2;
N = zeros(1, numel(data));
for ii = 1:numel(data) % Integer values only!
N(ii) = data(ii) * 10;
end
That your code is working for 0.25:0.25:2 is pure luck. This show how dangerous it is to use floating point expressions for indexing: It can work for some input, so there is no secure way for an exhaustive unit-testing.

카테고리

도움말 센터File Exchange에서 Elementary Math에 대해 자세히 알아보기

질문:

2022년 2월 18일

편집:

Jan
2022년 2월 18일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by