Non-Integer For-Loop

조회 수: 14 (최근 30일)
Christopher Schmiedl
Christopher Schmiedl 2021년 2월 16일
편집: David Goodmanson 2021년 2월 16일
I have what I hope is a relatively simple question. I am trying to construct a for loop over a value h from 0 to 1 with loop indices of 0.1 where there value of h will be plugged directly into an expression in the loop.
I tried the following:
dt = 0.1;
t = 0:dt:1;
nt = length(t);
%--------
for h = 1 : nt
Any assistance would be appreciated.

답변 (1개)

David Goodmanson
David Goodmanson 2021년 2월 16일
편집: David Goodmanson 2021년 2월 16일
Hi Christopher
for h = 0:.1:1
works, although with the interval expressed in floating point, you have to be careful.
for h = (0:10)/10
is safer, since the increment is an integer. If you are plugging the resulting value of h into some expression within the for loop there will be no problems. But if you are comparing h to some other value computed in the for loop, a la
if h == [some computed value]
you of course have to beware of floating point comparisons that might disagree in the 16th decimal place and give you an unwanted answer.

카테고리

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

태그

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by