开发者

When Iterating a MATLAB loop, it doesn't iterate up to the specified value -- Why?

开发者 https://www.devze.com 2023-02-28 16:31 出处:网络
t开发者_运维技巧he loop: for h=1:t_max REST OF CODE end if t_max is equal to 100, for example, the loop iterates only to 99 or t_max-1.

t开发者_运维技巧he loop:

for h=1:t_max
    REST OF CODE
end

if t_max is equal to 100, for example, the loop iterates only to 99 or t_max-1.

Anybody can help?


Is t_max a computed value? It may be ending up very close to 100 but not quite there, and due to rounding it would display as 100 in the default format setting. Here's an example using a smaller value of t_max:

>> t_max=4.9999999999999     

t_max =

    5.0000

Note how t_max looks like it's 5 when it's really a shade smaller than 5. In a for loop it would behave like this:

>> for i=1:t_max, disp(i),end
     1

     2

     3

     4

which has the appearance of only iterating to t_max - 1. But bumping up the format, and looking at t_max again will show the value with more precision:

>> format long; t_max

t_max =

   4.999999999999900


Check you are not modifying t_max in the body of the loop. The semantics of the for loop is such that it will execute t_max times, check the official documentation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号