Basic 'for loop' problem: it stops after several iterations
조회 수: 4 (최근 30일)
이전 댓글 표시
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
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)
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
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
댓글 수: 0
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
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
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.')
Or for this particular example, avoid the for loop entirely.
c2 = 0:0.1:1;
disp(c2.')
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!