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

5 次查看(过去 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
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 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by