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
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 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!