Basic 'for loop' problem: it stops after several iterations

조회 수: 4 (최근 30일)
Kuzan
Kuzan 2022년 11월 21일
댓글: Steven Lord 2022년 11월 21일
Hi all
Let me show you something interesting, so here is my code with a simple for loop:
clc;
c = zeros(11);
for a = 0:0.1:1
b = 10*a + 1;
c (1, b) = a;
end
It should work perfectly, but I got the errors, and the iterations stoped at the 7th when the a value was 0.6:
" Index in position 2 is invalid. Array indices must be positive integers or
logical values.
Error in delete (line 8)
c (1, b) = a;
"
Someone knows the reason? it is confusing. Thanks for your time.
  댓글 수: 1
Jan
Jan 2022년 11월 21일
Welcome to the world of numerical maths.
Your problem is very near to the frequently asked question: Why is 0.1 + 0.2 ~= 0.3? Another variant concerning the same effect:
any(0:0.1:1 == 0.3)
ans = logical
0
The most decimal number do not have an exact binary representation (and vice versa). Because computers use a binary representation of numbers usually (See: IEEE754), rounding effects are usual. This must be considered, when a result of a calculation with numbers having fractional parts or huge numbers > 2^53 is used for indexing or a comparison of floating point values.

댓글을 달려면 로그인하십시오.

답변 (2개)

KSSV
KSSV 2022년 11월 21일
I don't know why you are doing this, but the elow should work.
c = zeros(11);
for a = 0:0.1:1
b = 10*a + 1;
c (1, fix(b)) = a;
end

Image Analyst
Image Analyst 2022년 11월 21일
편집: Image Analyst 2022년 11월 21일
Because b is not an perfect integer. It has a small fractional part. This should have been taught in your linear algebra class or your numerical analysis class (it was for me). Google truncation error or rounding error.
clc;
c = zeros(11);
format long g
for a = 0:0.1:1
b = 10*a + 1;
fprintf('%.25f\n', b)
c (1, b) = a;
end
1.0000000000000000000000000 2.0000000000000000000000000 3.0000000000000000000000000 4.0000000000000000000000000 5.0000000000000000000000000 6.0000000000000000000000000 7.0000000000000008881784197
Index in position 2 is invalid. Array indices must be positive integers or logical values.
See the FAQ
There are several ways to fix it, for example you could round the values
clc;
c = zeros(11);
format long g
for a = 0:0.1:1
b = round(10*a + 1);
c (1, b) = a;
end
  댓글 수: 1
Steven Lord
Steven Lord 2022년 11월 21일
Another approach would be to iterate over a vector with integer entries. Use those values directly as indices and transform those values when you need to use them as data.
c = zeros(1, 11);
for a = 0:10
c(1, a+1) = a/10;
end
format longg
disp(c.')
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Or for this particular example, avoid the for loop entirely.
c2 = 0:0.1:1;
disp(c2.')
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by